【问题标题】:Why is `each` in ruby not defined in the enumerable module?为什么 ruby​​ 中的“each”没有在可枚举模块中定义?
【发布时间】:2015-02-21 01:29:20
【问题描述】:

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

我猜这是一个深思熟虑的选择,但我想知道为什么?

对于为什么 each 不包含在 Enumerable 中是否存在技术限制?

【问题讨论】:

  • 你将如何实现它?

标签: ruby enumerable


【解决方案1】:

来自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]

【讨论】:

  • 非常感谢 Ajedi32
猜你喜欢
  • 2015-01-05
  • 2013-03-07
  • 2016-08-06
  • 2019-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-03
相关资源
最近更新 更多