Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I properly chain custom methods in Ruby?

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)
like image 382
visBar Avatar asked Jul 08 '14 21:07

visBar


2 Answers

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)
like image 102
Rustam A. Gasanov Avatar answered Nov 15 '22 18:11

Rustam A. Gasanov


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
like image 36
merqlove Avatar answered Nov 15 '22 19:11

merqlove