fork download
  1. class RPN
  2. attr_reader :stack, :result
  3. def initialize
  4. @stack = []
  5. @result = 0
  6. end
  7. def clear_stack
  8. @stack = []
  9. end
  10. def pop()
  11. @stack.pop
  12. end
  13. def push(data)
  14. @stack << data.to_f
  15. end
  16. def operation(op)
  17. raise "Not enough numbers in the stack" if (@stack.length < 2)
  18. term1 = pop
  19. term2 = pop
  20. @result = eval("#{term2}#{op}#{term1}")
  21. @stack << @result
  22. end
  23. def evaluate(str)
  24. puts "Evaluating #{str}"
  25. str.split(' ').each do |el|
  26. '+-*/'.include?(el) ? operation(el) : push(el)
  27. end
  28. clear_stack
  29. @result
  30. end
  31. end
  32.  
  33. c = RPN.new
  34. p c.evaluate('1 2 3 4 5 6 7 8 9 10 + + + + + + + + +')
  35.  
Success #stdin #stdout 0.01s 8140KB
stdin
Standard input is empty
stdout
Evaluating 1 2 3 4 5 6 7 8 9 10 + + + + + + + + +
55.0