Created
February 6, 2013 19:48
-
-
Save kmandreza/4725226 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 InputError < StandardError | |
end | |
class RPNCalculator | |
DIGITS = /\A-?\d+\Z/ | |
ACCEPTABLE_INPUT = /\d+|[+*-\/]/ | |
def evaluate(list) | |
list_array = list.split | |
stack = [] | |
list_array.each do |element| | |
raise InputError if ACCEPTABLE_INPUT !~ element | |
if element =~ DIGITS | |
stack.push(element) | |
elsif stack.length > 1 | |
last_number = stack.pop | |
stack[-1] = (eval(stack[-1] + " #{element} " + last_number)).to_s | |
end | |
end | |
stack[0].to_i | |
end | |
end | |
calc = RPNCalculator.new | |
puts "The answer is:" | |
puts calc.evaluate(ARGV.first) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment