Last active
December 21, 2015 00:09
-
-
Save TGOlson/6218057 to your computer and use it in GitHub Desktop.
Reverse Polish Calculator - Version 1
(an example of what not to do)
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
# version 1 of 2 | |
# uses while loop and modifies array during looping (an example of what not to do) | |
# see version 2 here - https://gist.github.com/TGOlson/6218116 | |
class RPNCalculator | |
def evaluate(string) | |
array = string.split | |
i = 0 | |
while i < array.length | |
if array[i] =~ /\D/ #if current item is not a digit | |
case array[i] | |
when "+" then replace = add(array[i-2].to_i, array[i-1].to_i) | |
when "-" then replace = subtract(array[i-2].to_i, array[i-1].to_i) | |
when "*" then replace = multiply(array[i-2].to_i, array[i-1].to_i) | |
else puts "Invalid Operator." | |
end | |
array[i] = replace | |
array.slice!(i-2,2) | |
i -= 2 #rewind index after using slice! on array | |
end | |
i+=1 | |
end | |
array | |
end | |
def add(num1, num2) num1 + num2 end | |
def subtract(num1, num2) num1 - num2 end | |
def multiply(num1, num2) num1 * num2 end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment