Advertisement
Guest User

Untitled

a guest
May 8th, 2013
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.83 KB | None | 0 0
  1. # Reverse Polish Notation calculator
  2.  
  3. class RPNCalculator
  4.  
  5. def evaluate(string)
  6.  
  7. # create single array to push values and results to
  8. result = []
  9.  
  10. # now sort out the string and extract integers and operands
  11. string.split.each do |x|
  12.  
  13. if x == /\d/
  14. result << x.to_f
  15. elsif x == /\W/
  16. if x == "+"
  17. a = result.pop(2).inject(0) { |sum, e| sum + e }
  18. result.push(a)
  19. elsif x == "-"
  20. a = result.pop(2).inject(0) { |sum, e| e - sum }
  21. result.push(a)
  22. else
  23. a = result.pop(2).inject(0) { |prod, e| prod * e }
  24. result.push(a)
  25. end
  26. else
  27. result = 0
  28. end
  29.  
  30. return result
  31.  
  32. end
  33.  
  34. end
  35.  
  36. end
  37.  
  38. calc = RPNCalculator.new
  39.  
  40. p calc.evaluate("1 2 + 1 3 -")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement