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)
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)
Another way is to build pipeline via chainable_methods gem.
Described in the article
require 'chainable_methods'
module SimpleMath
include ChainableMethods
def add(a, b=0)
a + b
end
def subtract(a, b=0)
a - b
end
end
SimpleMath.
chain_from(5).
add(5).
add(5).
subtract(3).
unwrap
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With