Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Ruby version 1.9.3
- =begin
- 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.
- 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
- =end
- # define class MathDojo
- class MathDojo
- def initialize #constructor
- @sum = 10 #instance variable declared
- end
- def add(*numbers)# adds parameter(s) to instance variable sum
- numbers.inject(@sum) { |sum, number| sum + number }
- self
- end
- def subtract(*numbers) # subtracts parameter(s) from instance variable sum
- numbers.inject(@sum) { |sum, number| sum - number }
- self
- end
- end
- puts math1 = MathDojo.new.add(2).add(2, 5).subtract(3, 2)
Advertisement
Add Comment
Please, Sign In to add comment