1 class RPNError < RuntimeError 2 end 3 4 def rpneval(s) 5 a = Array.new 6 while s.length != 0 7 case s 8 when /^([\d.]+[eE]?[\d.]*)(.*)/ 9 a.push $1 10 when /^([-+*\/])(.*)/ 11 raise RPNError, "Not enough arguments" if a.length < 2 12 args = [eval(a.pop), eval(a.pop)] 13 a.push eval("#{args[1]} #{$1} #{args[0]}") 14 else 15 raise RPNError, "Syntax error after `#{s}'" 16 end 17 s = $2.strip 18 end 19 raise RPNError, "Stack not empty" if a.length != 1 20 return a.pop 21 end 22 23 puts rpneval(ARGV[0])