Skip to content

Instantly share code, notes, and snippets.

@Pcushing
Created June 15, 2012 03:25
Show Gist options
  • Save Pcushing/2934503 to your computer and use it in GitHub Desktop.
Save Pcushing/2934503 to your computer and use it in GitHub Desktop.
RPNCalculator with Andrew... crushing it
class RPNCalculator
def initialize
@rpn = []
end
def push(num)
@rpn << num
end
def plus
do_equation(:+)
end
def minus
do_equation(:-)
end
def times
do_equation(:*)
end
def divide
do_equation(:/)
end
def value
@rpn[-1]
end
def do_equation(op_symbol)
operators = { :+ => lambda{ @rpn[-2] + @rpn[-1] },
:- => lambda{ @rpn[-2] - @rpn[-1] },
:* => lambda{ @rpn[-2] * @rpn[-1] },
:/ => lambda{ @rpn[-2].to_f / @rpn[-1] } }
result = operators[op_symbol].call
2.times { @rpn.slice!(-1) }
@rpn << result
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment