Created
July 1, 2013 16:26
-
-
Save fabianuribe/5902340 to your computer and use it in GitHub Desktop.
Recursive RPN Calculator without iteration (inject, each, map, etc. not allowed)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def evaluate(string, answer=[]) | |
return answer[0] if string.empty? | |
expressions = string.split(' ') | |
obj = expressions.shift | |
if obj.to_s[/\d+/] | |
answer << obj.to_f | |
else ["*","+","-","/"].include?(obj) | |
operands = answer.pop(2) | |
answer << (operands[0].send(obj,operands[1])) | |
end | |
evaluate(expressions.join(' '), answer) | |
end | |
puts evaluate('1 2 +') == 3 # => 3 | |
puts evaluate('2 5 *') == 10 # => 10 | |
puts evaluate('3 50 20 - +') == 33 # => 30 | |
puts evaluate('70 10 4 + 5 * -') == 0 # => 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice! I re-did the RPN calculator a few days ago and my code is very similar. I didn't know you could use
operands = answer.pop(2)
I did
operand_one, operand_two = answer.pop, answer.pop