Skip to content

Instantly share code, notes, and snippets.

@andyjbas
Created January 21, 2013 18:26
Show Gist options
  • Save andyjbas/4588121 to your computer and use it in GitHub Desktop.
Save andyjbas/4588121 to your computer and use it in GitHub Desktop.
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