Skip to content

Instantly share code, notes, and snippets.

@nibanez80
Created March 8, 2013 18:43
Show Gist options
  • Save nibanez80/5118750 to your computer and use it in GitHub Desktop.
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…
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