Guest User

Untitled

a guest
Apr 21st, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1. class BinaryOperator
  2. def operate(stack)
  3. y = stack.pop
  4. x = stack.pop
  5. stack.push binary_operate(x, y)
  6. end
  7. end
  8.  
  9. class Addition < BinaryOperator
  10. protected
  11. def binary_operate(x, y)
  12. x + y
  13. end
  14. end
  15.  
  16. class Subtraction < BinaryOperator
  17. protected
  18. def binary_operate(x, y)
  19. x - y
  20. end
  21. end
  22.  
  23. class Multiplication < BinaryOperator
  24. protected
  25. def binary_operate(x, y)
  26. x * y
  27. end
  28. end
  29.  
  30. class Division < BinaryOperator
  31. protected
  32. def binary_operate(x, y)
  33. x / y
  34. end
  35. end
  36.  
  37. class Factorial
  38. def operate(stack)
  39. stack.push factorial(stack.pop)
  40. end
  41.  
  42. private
  43. def factorial(i)
  44. (2..i).inject { |x,y| x * y }
  45. end
  46. end
  47.  
  48. class OperatorFactory
  49. def self.create_operator(token)
  50. case token
  51. when '+' then Addition.new
  52. when '-' then Subtraction.new
  53. when '*' then Multiplication.new
  54. when '/' then Division.new
  55. when '!' then Factorial.new
  56. end
  57. end
  58. end
  59.  
  60. class Calculator
  61. def evaluate(*tokens)
  62. stack = []
  63. tokens.each do |token|
  64. if token =~ /\d+/ then
  65. stack.push token.to_i
  66. else
  67. op = OperatorFactory.create_operator token
  68. op.operate(stack)
  69. end
  70. end
  71. stack.pop
  72. end
  73. end
  74.  
  75. c = Calculator.new
  76. puts c.evaluate('2', '3', '+', '!')
Add Comment
Please, Sign In to add comment