m.divya.mohan m.divya.mohan - 2 months ago 18
Ruby Question

Evaluate an expression stored in an array

I have an array which is interleaved with sign (+/-) and numbers.
Is there a way to evaluate this array in ruby?

e.g:

["+", 1, "+", 2, "+", 3]
.
This needs to be evaluated, ie, to
6
in above case.

More examples:

["+", 1, "+", 2, "+", 3] -> 6
["+", 1, "+", 2, "-", 3] -> 0
["-", 1, "-", 2, "-", 3] -> -6

Answer

For the given array structure the code could be like

ar = ["-", 1, "-", 2, "-", 3]
ar.each_slice(2).inject(0) do |memo, slice|
  # memo.send(slice[0], slice[1])
  memo.send(*slice) # thanks @tadman!
end
# => -6
Comments