Module: Trxl::AvgFunction2

Defined in:
lib/trxl/trxl_grammar.rb

Instance Method Summary collapse

Instance Method Details

#eval(env = Environment.new) ⇒ Object



7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
# File 'lib/trxl/trxl_grammar.rb', line 7084

def eval(env = Environment.new)
  strict = true
  nr_of_vals = 0
  values = expressions
  strict_flag = values[0].eval(env)
  if strict_flag.is_a?(TrueClass) || strict_flag.is_a?(FalseClass)
    values.shift
    strict = strict_flag
  end

  # if all values are nil return nil
  values = values.map { |v| v.eval(env) }
  return nil if values.compact.size == 0

  s = values.inject(0) do |sum, next_val|
    sum + if next_val.is_a?(Array)
      next_val.flatten.inject(0) do |next_sum, val|
        nr_of_vals += 1 if val && (strict || (!strict && val != 0))
        next_sum + (val || 0)
      end
    else
      nr_of_vals += 1 if next_val && (strict || (!strict && next_val != 0))
      next_val || 0
    end
  end
  (s != 0 && nr_of_vals != 0) ? s.to_f / nr_of_vals : 0
end

#expressionsObject



7112
7113
7114
# File 'lib/trxl/trxl_grammar.rb', line 7112

def expressions
  [ expression ] + more_expressions.elements.map { |e| e.expression }
end