def evaluate expr stack = [] expr.split(/\s+/).each do |token| stack << case token when /^-?\d*$/ token.to_i when /^[+\-*\/]$/ right, left = stack.pop, stack.pop raise "Stack underflow" unless left and right left.send token, right else raise "Invalid token: #{token}" end end stack.length == 1 or raise "Invalid stack: #{stack}" stack[0] end