Skip to content

Instantly share code, notes, and snippets.

@Stephenitis
Last active December 14, 2015 15:08
Show Gist options
  • Save Stephenitis/5105048 to your computer and use it in GitHub Desktop.
Save Stephenitis/5105048 to your computer and use it in GitHub Desktop.
RPN Exercise
class RPNCalculator
def evaluate(expression) # expression = '1 2 +'
operators = ["+", "-", "*"]
stack = []
array = expression.split(" ") # ["1", "2", "+"]
array.each do |i|
if operators.include?(i)
second_operand = stack.pop #is defining a variable that takes the
first_operand = stack.pop
stack.push(first_operand.send(i, second_operand))
#pushes 1 to stack [1]
#pushes 2 to stack ["1","2"]
#pops first second operand our of stack sends to variable
#pops first operand out of stack and sends to variable
#pushes first operand 1 sends the operator (+) and then second operand
#take first operand and sends it a operator and the second operand
else
stack.push(i.to_i)
end
end
stack.pop
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment