Last active
December 17, 2015 19:28
-
-
Save mattmawhinney/5660228 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 | |
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