为什么ruby中的`each`没有在可枚举模块中定义?

时间:2014-12-22 22:21:18

标签: ruby enumerable

Ruby在可枚举中定义了大多数迭代器方法,并在Array,Hash等中包含了这些方法。 但是each在每个类中定义,不包括在可枚举中。

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

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

1 个答案:

答案 0 :(得分:6)

来自Enumerable的文档:

  

Enumerable mixin为集合类提供了多种遍历和搜索方法,并具有排序功能。 该类必须提供每个方法,这会产生集合的连续成员。

因此,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]