Created
April 8, 2013 19:58
-
-
Save dhouk24/5339968 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 | |
# I'm starting with a simple example of ('1 2 +') to work on this problem | |
# Here is my gameplan: I want to iterate through the array until I hit an operator symbol | |
# If its not an operator symbol I want to remove the first item and add it to the back of the array | |
# Once I get to an operator symbol I will perform that function on the last two numbers of the array | |
# My problem is that it goes through the array once and pushes the 1 to the back, but then when it hits the "2", | |
# it triggers the if x == "+" statement | |
# Can someone explain to me why it does not push the 2 to the back of the array the same way it does with the 1? | |
def evaluate(string) | |
start_array = string.split(/ /) | |
start_array.each do |x| | |
puts start_array.inspect # This statement prints out ["1", "2", "+"] and then ["2", "+", 1] | |
if x == "+" | |
num1 = start_array.pop | |
num2 = start_array.pop | |
puts num2 # This returns the '+' which is why it returns the can't convert Fixnum into string error | |
start_array << num2 + num1 | |
start_array.shift | |
else | |
x = start_array.shift | |
start_array << x.to_i | |
end | |
end | |
end | |
end | |
my_calc = RPNCalculator.new | |
my_calc.evaluate('1 2 +') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment