I'm working on an RPN Calculator and think I'm almost there, except it's returning the expression not the solution.
def evaluate(expression)
expression = expression.split
operators = expression.select { |v| v =~ /\W/}
operands = expression.select { |v| v =~ /\d/}
new_expression = operands.zip(operators)
eval = new_expression.join
end
This should return -7
:
puts evaluate('5 8 + 4 - 5 *')
#=> 5+8-4*5
eval = new_expression.join
This calls new_expression.join
and stores the result in a local variable called eval
. Since you never use that local variable, you could as well just have written:
new_expression.join
If it was your intention to call Ruby's eval
method with the result of new_expression.join
as its argument, you should remove the assignment operator:
eval new_expression.join
That said using eval
to evaluate the expression is only a good idea if you're only ever evaluating trusted input.