Ruby Method / Array

How to implement '<<to have the same behavior when used as a chain 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 to give the same result.

+3
source share
2 answers

Add selfas the last line in the <method to return it. Like you, you implicitly return an array, not an instance.

+4
source

Explanation of the answer above:

When a method is bound, the following method is applied to the result of the first method.

Example:

class A
  def method1
    B.new
  end
end

class B
  def method2
    C.new
  end
end

class C
  def method3
    puts "It is working!!!"
  end
end

The code below will work

A.new.method1.method2.method3

but it will not be

A.new.method1.method3.method2

because the instance of class B resulting from A.new.method1 does not implement method3. It is the same:

(((A.new).method1).method3).method2

, , , Test Array < , Test # < < self, @internal_array.

0

Source: https://habr.com/ru/post/1757410/


All Articles