How can I properly chain custom methods in Ruby?
method-chaining, methods, ruby, ruby-on-rails
Solution
Are you trying to do something like this?
class SimpleMath
def initialize
@result = 0
end
#1 add function
def add(val)
@result += val
self
end
#2 Subtract function
def subtract(val)
@result -= val
self
end
def to_s
@result
end
end
newNumber = SimpleMath.new
p newNumber.add(2).add(2).subtract(1)
For any number of arguments
class SimpleMath
def initialize
@result = 0
end
#1 add function
def add(*val)
@result += val.inject(&:+)
self
end
#2 Subtract function
def subtract(*val)
@result -= val.inject(&:+)
self
end
def to_s
@result
end
end
newNumber = SimpleMath.new
p newNumber.add(1, 1).add(1, 1, 1, 1).subtract(1)
Problem
I am trying to do a chaining method for the following two methods. After running this code, I kept getting the following output: ``` #<SimpleMath:0x007fc85898ab70>% ``` My question is: what is the proper way of chaining methods in `Ruby`? Here is my codes: ``` class SimpleMath def add(a,b=0) a + b return self end def subtract(a,b=0) a - b return self end end newNumber = SimpleMath.new() print newNumber.add(2,3).add(2) ```