Skip to content

Instantly share code, notes, and snippets.

@Vanderln
Created March 13, 2013 14:22
Show Gist options
  • Save Vanderln/5152605 to your computer and use it in GitHub Desktop.
Save Vanderln/5152605 to your computer and use it in GitHub Desktop.
RPN Calculator
class RPNCalculator
def evaluate(input)
array = input.split
array.each do |x|
case
when x == "+"
op_index = array.index(x)
add = array[op_index-2].to_i + array[op_index - 1].to_i
array.insert(op_index + 1, add)
array.slice!(op_index -2, op_index)
puts array.inspect
puts op_index
when x == "-"
op_index = array.index(x)
minus = array[op_index-2].to_i - array[op_index - 1].to_i
array.insert(op_index + 1, minus)
array.slice!(op_index -2, op_index)
puts array.inspect
puts op_index
when x == "*"
op_index = array.index(x)
multi = array[op_index-2].to_i * array[op_index - 1].to_i
array.insert(op_index + 1, multi)
array.slice!(op_index -2, op_index)
puts array.inspect
puts op_index
else
end
end
#array.first.to_i
end
end
#calc = RPNCalculator.new
#puts calc.evaluate('1 2 +')
#calc = RPNCalculator.new
#puts calc.evaluate('2 5 *')
calc = RPNCalculator.new
puts calc.evaluate('70 10 4 + 5 * -')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment