Created
March 8, 2013 18:43
-
-
Save nibanez80/5118750 to your computer and use it in GitHub Desktop.
Exercise: Implement a Reverse Polish notation calculator
Create an RPNCalculator class which can evaluate expressions written in Reverse Polish notation. It should have an evaluate instance method which takes as its input a valid RPN expression and returns its evaluation. Your calculator only needs to handle addition, multiplication, and subtrac…
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(expression) | |
| array = expression.split(' ') | |
| until array.length == 1 | |
| array.each_with_index do |item, index| | |
| if item == "+" || item == "*" || item == "-" | |
| array[index] = eval(array[index - 2] + array[index] + array[index - 1]).to_s | |
| array.delete_at(index - 1) | |
| array.delete_at(index - 2) | |
| end | |
| end | |
| end | |
| array.join.to_i | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment