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

标签 ruby enumerable

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

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

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

最佳答案

来自 Enumerable 的文档:

The Enumerable mixin provides collection classes with several traversal and searching methods, and with the ability to sort. The class must provide a method each, which yields successive members of the collection.

因此 Enumerable 模块要求包含它的类自己实现 each。 Enumerable 中的所有其他方法都取决于 each 由包含 Enumerable 的类实现。

例如:

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]

关于ruby - 为什么 ruby​​ 中的 `each` 没有定义在可枚举模块中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27611324/

相关文章:

ruby - 如何按空格或点拆分字符串?

ruby-on-rails - Rails 中的分组和求和

c# - LINQ IEnumerable 在底层是如何工作的?

ruby - 惰性枚举直到 block 为假

ruby - 当您的类未定义#each 时,返回 Enumerator::Lazy 的最佳方法是什么?

采用数组或多个参数的 Ruby block

ruby-on-rails - 无法解释的 "can' t修改卡住对象”异常

ruby - 用 nil 填充堆栈并将 "top"解释为最后一个非 nil 值是否有一些优势?

ruby - Textmate 中损坏的切换评论

Python:通过字符串列表递归 - 如何区分?