-
-
Save stefanosc/13c82651547bf4a6fc24 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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