Ruby可链式方法/数组

时间:2010-07-30 20:21:37

标签: ruby arrays chainable

如何实施'<<<用作可链式方法时具有相同的行为?

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?

我希望两种情况都给出相同的结果。

2 个答案:

答案 0 :(得分:4)

添加self作为&lt;&lt;的最后一行返回它的方法。你是隐式返回数组,而不是实例。

答案 1 :(得分:0)

上述答案的解释:

当链接方法时,下一个方法将应用于第一个方法的结果。

例如:

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

以下代码可以使用

A.new.method1.method2.method3

但这不会

A.new.method1.method3.method2

因为B.new.method1的结果是B类的实例没有实现method3。这是相同的:

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

上面问题中使用的代码更多一点,因为Test和Array都有方法&lt;&lt;。但我想要测试#&lt;&lt;返回自己,而不是返回的@internal_array。