Skip to content

Instantly share code, notes, and snippets.

@siong1987
Created April 17, 2013 07:47
Show Gist options
  • Save siong1987/5402499 to your computer and use it in GitHub Desktop.
Save siong1987/5402499 to your computer and use it in GitHub Desktop.
class Calculator
def evaluate statement
symbols = statement.split(' ')
puts calculate(symbols)
end
def calculate symbols
if symbols.length == 1
return symbols[0]
else
queue = []
symbols.length.times do
symbol = symbols.shift
if symbol == '+'
result = queue.pop.to_i + queue.pop.to_i
queue << result
break
elsif symbol == '-'
result = queue.pop.to_i - queue.pop.to_i
queue << result
break
elsif symbol == '*'
result = queue.pop.to_i * queue.pop.to_i
queue << result
break
elsif symbol == '/'
result = queue.pop.to_i / queue.pop.to_i
queue << result
break
else
queue << symbol
end
end
queue.length.times do
symbols.unshift(queue.pop)
end
calculate(symbols)
end
end
end
c = Calculator.new
c.evaluate("70 10 4 + 5 * -")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment