Skip to content

Instantly share code, notes, and snippets.

@heftig
Last active August 29, 2015 14:14
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 heftig/ae6498233a06b813d464 to your computer and use it in GitHub Desktop.
Save heftig/ae6498233a06b813d464 to your computer and use it in GitHub Desktop.
def evaluate(expression)
stack = []
expression.split.each do |word|
case word
when "+"
stack << (stack.pop + stack.pop)
when "-"
arg1 = stack.pop
arg2 = stack.pop
stack << (arg2 - arg1)
when "*"
stack << (stack.pop * stack.pop)
when "/"
arg1 = stack.pop
arg2 = stack.pop
stack << (arg2 / arg1)
else
stack << Float(word)
end
end
stack.last
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment