rubyarrayschainable

Ruby chainable method / array


How do I implement the '<<' to have the same behavior when used as a chainable method?

class Test
  attr_accessor :internal_array

  def initialize
    @internal_array = []
  end

  def <<(item)
    @internal_array << :a
    @internal_array << item
  end
end

t = Test.new
t << 1
t << 2
t << 3
#t.internal_array => [:a, 1, :a, 2, :a, 3]
puts "#{t.internal_array}" # => a1a2a3

t = Test.new
t << 1 << 2 << 3
#t.internal_array => [:a, 1, 2, 3]
puts "#{t.internal_array}" # => a123 , Why not a1a2a3?

I want both cases giving the same result.


Solution

  • Add self as the last line in the << method to return it. As is, you're implicitly returning the array, not the instance.