Skip to content

Instantly share code, notes, and snippets.

@fabianuribe
Created July 1, 2013 16:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fabianuribe/5902340 to your computer and use it in GitHub Desktop.
Save fabianuribe/5902340 to your computer and use it in GitHub Desktop.
Recursive RPN Calculator without iteration (inject, each, map, etc. not allowed)
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
@in15
Copy link

in15 commented Jul 1, 2013

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment