Reputation: 71
I'm very new to Ruby and I'm trying to use math symbols that are stored in an array as strings to perform math. This is for a Reverse Polish Notation calculator I'm working on. For example:
var = ['1','2','+']
I've puzzled through enough regular expressions to figure out how to differentiate numbers from non-numbers in an if statement, but I'm trying to figure out how I could make the following work to produce -1.
var[0] var[2] var[1] #=> 1 - 2
Does anyone know how to change the string '-' back into the math symbol?
Upvotes: 2
Views: 255
Reputation: 29094
'1'.to_i.send('-', '2'.to_i)
# => -1
send
calls the first argument as a method on the object, with the remaining arguments as parameters.
Upvotes: 4
Reputation: 3412
One way to do this is using the eval
function
result = eval "#{var[0]} #{var[2]} #{var[1]}"
Upvotes: 1