2014-12-22 35 views
3

Ruby在enumerable中定义了大多数迭代器方法,并且包含在Array,Hash等中。 但是each定义在每个类中,并且不包含在enumerable中。为什么ruby中的'each`没有在可枚举模块中定义?

我猜这是一个故意的选择,但我想知道为什么?

是否存在技术限制,为什么each未包含在Enumerable中?

+1

你将如何实现呢? –

回答

6

从文档Enumerable

可枚举混入提供的集合类与几个遍历和搜索方法,以及排序的功能。 这个类必须提供一个方法,每个方法产生集合的连续成员。

所以Enumerable模块要求包含它的类自己实现each。 Enumerable中的所有其他方法都依赖于由包含Enumerable的类实现的each

例如:

class OneTwoThree 
    include Enumerable 

    # OneTwoThree has no `each` method! 
end 

# This throws an error: 
OneTwoThree.new.map{|x| x * 2 } 
# NoMethodError: undefined method `each' for #<OneTwoThree:0x83237d4> 

class OneTwoThree 
    # But if we define an `each` method... 
    def each 
    yield 1 
    yield 2 
    yield 3 
    end 
end 

# Then it works! 
OneTwoThree.new.map{|x| x * 2 } 
#=> [2, 4, 6] 
+0

谢谢你真的很欣赏Ajedi32 – mrageh

相关问题