2010-03-13 88 views

回答

5

你真的只需要委託給@array上的每個方法並將它傳遞給它。此外,還可以包括可枚舉混入物,以獲取其提供的方法(如地圖,注射,等...):

可枚舉模塊上
class Box 
    include Enumerable 

    def initialize 
    @array = [:foo, :bar] 
    end 

    def each(&block) 
    @array.each(&block) 
    end 
end 

更多信息,請in the documentation

+0

謝謝,帕特里克! – 2010-03-13 12:31:58

+0

+1 - 這是相當不錯的解決方案。 – RubyDubee 2010-03-13 15:22:26

+0

Forwardable庫是處理簡單委託的另一種方式:'require'forwardable'',然後在Box中:'extend Forwardable'和'def_delegator(:@ array,:each)' – 2010-03-14 21:25:12

1

對於這個簡單的例子,實際上並不需要通過明確塊:

def each     
    @array.each{|e| yield e} 
end 

傳遞塊(這是一個Proc object)明確允許您以測試它的東西,比如參數的個數,該公司預計:

class Box 
    ...  
    def each(&block) 
    @array.each do |e| 
     case block.arity 
     when 0 
     yield 
     when 1 
     yield e 
     when 2 
     yield e, :baz 
     else 
     yield 
     end 
    end 
    end 
end 

a = Box.new 
a.each { puts "nothing" }    # displays "nothing, nothing" 
a.each { |e| puts e }     # displays "foo, bar" 
a.each { |e1, e2| puts "#{e1} #{e2}" } # displays "foo baz, bar baz" 
+0

非常感謝,Nate。我會研究你的答案^^ – 2010-03-13 12:32:50

相關問題