2013-10-10 44 views
0

如何從我的數組包裝中返回枚舉器而不使用已有的數組迭代器?返回枚舉器不使用現有的迭代器

class MyArray 

    def initialize 
    @inner = [] 
    end 

    def each 
    index = 0 
    while index < @inner.size 
     yield @inner[index] if block_given? 
     index += 1 
    end 
    end 
end 

我無法弄清楚如何避免在each方法結束通話之類的東西@inner.each

+0

@sawa我修好了。有一個命名不匹配。 –

+1

@sawa好的,'class'之前有一個額外的'def'。 –

回答

1

考慮:

@inner = [1, 2, 3] 

代碼

@inner.to_enum 

會返回一個枚舉。

enum = @inner.to_enum 
enum.each{|e| p e} 
# => 1, 2, 3 
+1

謝謝你的解決方案,代碼更正和英文更正:) –

+0

很高興知道它有幫助。 – sawa