fork download
  1. class Calc
  2. attr_reader :sum
  3.  
  4. def initialize
  5. @operation = nil
  6. @sum = 0
  7. end
  8.  
  9. def plus
  10. @operation = ->(a,b){ a + b }
  11. self
  12. end
  13.  
  14. def minus
  15. @operation = ->(a,b){ a - b }
  16. self
  17. end
  18.  
  19. def times
  20. @operation = ->(a,b){ a * b }
  21. self
  22. end
  23.  
  24. def divided_by
  25. @operation = ->(a,b){ a.fdiv(b) }
  26. self
  27. end
  28.  
  29. def one
  30. operate(1)
  31. self
  32. end
  33.  
  34. def two
  35. operate(2)
  36. self
  37. end
  38.  
  39. def three
  40. operate(3)
  41. self
  42. end
  43.  
  44. def to_s
  45. @sum
  46. end
  47.  
  48. def inspect
  49. @sum
  50. end
  51.  
  52. private
  53.  
  54. def operate(value)
  55. if @operation
  56. @sum = @operation.(@sum, value)
  57. @operation = nil
  58. else
  59. @sum = value
  60. end
  61. end
  62. end
  63.  
  64. p Calc.new.one.plus.two
  65. p Calc.new.one.minus.two.divided_by.three
Success #stdin #stdout 0.02s 7464KB
stdin
Standard input is empty
stdout
3
-0.3333333333333333