gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 07:49:47 26 4
gpt4 key购买 nike

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com