Skip to content

Instantly share code, notes, and snippets.

@mjhea0
Last active December 16, 2015 22:09
Show Gist options
  • Select an option

  • Save mjhea0/5504869 to your computer and use it in GitHub Desktop.

Select an option

Save mjhea0/5504869 to your computer and use it in GitHub Desktop.
rpn calculator
class RPNCalculator
def evaluate(rpn)
expression = rpn.split
stack = Array.new
unless expression.count > 1
return expression[0].to_i
end
expression.each do |e|
if e == "+" || e == "-" || e == "*" || e == "/"
op2 = stack.pop.to_i
stack.push(stack.pop.to_i.send e, op2).to_s
else
stack << e
end
end
puts stack.first
end
end
# calc = RPNCalculator.new
# calc.evaluate('1 2 +') # => 3
# calc.evaluate('2 5 *') # => 10
# calc.evaluate('50 20 -') # => 30
# calc.evaluate('10 2 /') # => 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment