Created
June 15, 2012 03:25
-
-
Save Pcushing/2934503 to your computer and use it in GitHub Desktop.
RPNCalculator with Andrew... crushing it
This file contains hidden or 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
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