Skip to content

Instantly share code, notes, and snippets.

@stefanosc
Created September 26, 2014 19:31
Show Gist options
  • Save stefanosc/13c82651547bf4a6fc24 to your computer and use it in GitHub Desktop.
Save stefanosc/13c82651547bf4a6fc24 to your computer and use it in GitHub Desktop.
class RPNCalculator
def evaluate(rpn_expr)
begin
count = 0
result = rpn_expr.split(' ').each_with_object([]) do |item,arr|
item.match(/(\A-?\d+\z)|(\A[\+\-\*]\z)/) do
if $1
count += 1
arr << item.to_i
else
count -= 1
raise ArgumentError.new("not enough digits!") if count < 1
arr[-2..-1] = ( arr[-2].send(item, arr[-1]) )
end
end or raise ArgumentError.new("malformed RPN expression!")
end
count == 1 && result.first or raise ArgumentError.new("too many digits!")
rescue ArgumentError => e
e.message
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment