Skip to content

Instantly share code, notes, and snippets.

@mattmawhinney
Last active December 17, 2015 19:28
Show Gist options
  • Save mattmawhinney/5660228 to your computer and use it in GitHub Desktop.
Save mattmawhinney/5660228 to your computer and use it in GitHub Desktop.
class RPNCalculator
def initialize(expression)
@expression = expression
end
def evaluate(expression)
container = @expression.split(' ')
num_container = []
container.each do |x|
if !(x == '+' || x == '-' || x == '*')
num_container << x
elsif x == '+'
add = num_container[-2].to_i + num_container[-1].to_i
2.times do
num_container.pop
end
num_container << add
elsif x == '-'
dif = num_container[-2].to_i - num_container[-1].to_i
2.times do
num_container.pop
end
num_container << dif
elsif x == '*'
mult = num_container[-2].to_i * num_container[-1].to_i
2.times do
num_container.pop
end
num_container << mult
end
end
num_container
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment