2010-07-30 61 views
3

如何在執行'< <'作爲可鏈式方法時具有相同的行爲?Ruby鏈式方法/數組

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? 

我希望這兩種情況都給出相同的結果。

回答

4

添加self作爲< <方法的最後一行返回它。因爲你隱式地返回數組,而不是實例。

0

上述答案的說明:

當一個方法被鏈接,下一個方法被施加到第一種方法的結果。

對於exemplo:

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,這是的結果的一個實例A.new.method1不執行method3。這是相同的:

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

在上面的問題中使用的代碼,是多一點點技巧,因爲兩者,測試和陣列有方法< <。但是我想測試#< <返回self,而不是返回的@internal_array。

+0

這是應該回答你的問題嗎?我很困惑。 – Chuck 2010-07-30 21:24:44

+0

這是對上述答案的解釋。馬修給出了簡短的回答:在...上添加自我... – Portela 2010-08-04 04:30:18