Skip to content

Instantly share code, notes, and snippets.

@fabianuribe
Created July 1, 2013 15:23
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/5901803 to your computer and use it in GitHub Desktop.
Save fabianuribe/5901803 to your computer and use it in GitHub Desktop.
RPN Calculator
class RPNCalculator
def initialize
end
def evaluate(rpn)
expressions = rpn.split(' ')
ans = []
expressions.each do |obj| # example: (5 1 2 + 4 * + 3 -)
if obj.to_s[/[0-9]+/]
ans << obj.to_i
else ["*","+","-"].include?(obj)
operands = ans.pop(2)
ans << (operands[0].send(obj,operands[1]))
end
end
ans[0]
end
end
puts calc = RPNCalculator.new
puts calc.evaluate('1 2 +') == 3 # => 3
puts calc.evaluate('2 5 *') == 10 # => 10
puts calc.evaluate('50 20 -') == 30 # => 30
puts calc.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