Skip to content

Instantly share code, notes, and snippets.

@kmandreza
Created February 6, 2013 19:48
Show Gist options
  • Save kmandreza/4725226 to your computer and use it in GitHub Desktop.
Save kmandreza/4725226 to your computer and use it in GitHub Desktop.
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