HeidiHeff

Ruby class method chaining - HELP!

Sep 10th, 2013
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 0.89 KB | None | 0 0
  1.  
  2. # Ruby version 1.9.3
  3. =begin
  4. Directions: HINT: To do this exercise, you will probably have to use 'return self'.  If the method returns itself (an instance of itself), we can chain methods.
  5.  
  6. Develop a ruby class called MathDojo that has the following functions: add, subtract. Have these 2 functions take at least 1 parameter. MathDojo.new.add(2).add(2, 5).subtract(3, 2) should perform 0+2+(2+5)-(3+2) and return 4
  7. =end
  8.  
  9. # define class MathDojo
  10. class MathDojo
  11.  
  12.   def initialize #constructor
  13.     @sum = 10 #instance variable declared
  14.   end
  15.  
  16.   def add(*numbers)# adds parameter(s) to instance variable sum
  17.     numbers.inject(@sum) { |sum, number| sum + number }
  18.     self
  19.   end
  20.  
  21.   def subtract(*numbers) # subtracts parameter(s) from instance variable sum
  22.     numbers.inject(@sum) { |sum, number| sum - number }
  23.     self
  24.   end
  25. end
  26.  
  27. puts math1 = MathDojo.new.add(2).add(2, 5).subtract(3, 2)
Advertisement
Add Comment
Please, Sign In to add comment