Created
January 21, 2013 18:26
-
-
Save andyjbas/4588121 to your computer and use it in GitHub Desktop.
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
class RPNCalculator | |
attr_accessor :stack | |
def initialize | |
self.stack = Array.new | |
end | |
def push(val) | |
self.stack.push(val.to_f) | |
end | |
def plus | |
eval(:+) | |
end | |
def minus | |
eval(:-) | |
end | |
def times | |
eval(:*) | |
end | |
def divide | |
eval(:/) | |
end | |
def value | |
self.stack.last | |
end | |
private | |
def eval(operation) | |
# raise "calculator is empty" unless self.stack.size >= 2 | |
op1 = self.stack.pop | |
op2 = self.stack.pop | |
case operation | |
when :+ | |
val = op1 + op2 | |
when :- | |
val = op2 - op1 | |
when :* | |
val = op1 * op2 | |
when :/ | |
val = op2 / op1 | |
end | |
self.stack << val | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment