【发布时间】:2015-02-21 01:29:20
【问题描述】:
Ruby 在可枚举中定义了大多数迭代器方法,包括在 Array、Hash 等中。
但是each 是在每个类中定义的,并且不包含在可枚举中。
我猜这是一个深思熟虑的选择,但我想知道为什么?
对于为什么 each 不包含在 Enumerable 中是否存在技术限制?
【问题讨论】:
-
你将如何实现它?
标签: ruby enumerable
Ruby 在可枚举中定义了大多数迭代器方法,包括在 Array、Hash 等中。
但是each 是在每个类中定义的,并且不包含在可枚举中。
我猜这是一个深思熟虑的选择,但我想知道为什么?
对于为什么 each 不包含在 Enumerable 中是否存在技术限制?
【问题讨论】:
标签: ruby enumerable
来自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]
【讨论】: