Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Reverse Polish Notation calculator
- class RPNCalculator
- def evaluate(string)
- # create single array to push values and results to
- result = []
- # now sort out the string and extract integers and operands
- string.split.each do |x|
- if x == /\d/
- result << x.to_f
- elsif x == /\W/
- if x == "+"
- a = result.pop(2).inject(0) { |sum, e| sum + e }
- result.push(a)
- elsif x == "-"
- a = result.pop(2).inject(0) { |sum, e| e - sum }
- result.push(a)
- else
- a = result.pop(2).inject(0) { |prod, e| prod * e }
- result.push(a)
- end
- else
- result = 0
- end
- return result
- end
- end
- end
- calc = RPNCalculator.new
- p calc.evaluate("1 2 + 1 3 -")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement