Created
September 7, 2012 16:03
-
-
Save dgamboa/3667422 to your computer and use it in GitHub Desktop.
Reverse Polish Notation Calculator
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
| # The following method will take strings like '5 4 +', '-1', '5 -3 4 + 6 9 - * +', and '2 3 4 7 + * -', and return the result of running the calculation. | |
| # Note: when performing division it will always round down. | |
| def evaluate(string) | |
| return string.to_i unless string.include?(' ') | |
| string.match /(-?\d+) (-?\d+) ([-+*\/])(?!\d)/ | |
| result = ($1.to_i).send($3,$2.to_i) | |
| string.gsub!($1 + ' ' + $2 + ' ' + $3, result.to_s) | |
| evaluate(string) | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment