Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 736
Portela Avatar asked Dec 31 '25 22:12

Portela


1 Answers

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

like image 115
Matthew Flaschen Avatar answered Jan 03 '26 12:01

Matthew Flaschen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!