考虑以下几点:
enum = Enumerator.new do |x|
x << "hello"
x << "world"
end
enum.take(1)
#=> ["hello"]
enum.take(100)
#=> ["hello", "world"]
这是怎么回事?
好吧,产生的变量x 是Enumerator::Yielder 的一个实例。每当您对变量调用 << 或 yield 时,都会将一个值附加到最终的结果数组中。
enum.take(n) 表示“尝试为此枚举收集最多 n 值”。
所以,回顾你原来的例子,我们有:
loop do
x << a
a *= 2
end
因为你在枚举上调用了take(4),所以Enumerator::Yielder会立即知道返回,如果收集了4项。
...另一方面,如果您尝试运行,例如enumer.to_a 然后循环将永远持续下去 - 因为它没有任何条件提前退出!
根据我的发现,关于其工作原理的 ruby 文档有点少;但是有this helpful description of the behaviour in the source code:
/*
* call-seq:
* Enumerator.new(size = nil) { |yielder| ... }
* Enumerator.new(obj, method = :each, *args)
*
* Creates a new Enumerator object, which can be used as an
* Enumerable.
*
* In the first form, iteration is defined by the given block, in
* which a "yielder" object, given as block parameter, can be used to
* yield a value by calling the +yield+ method (aliased as +<<+):
*
* fib = Enumerator.new do |y|
* a = b = 1
* loop do
* y << a
* a, b = b, a + b
* end
* end
*
* p fib.take(10) # => [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
*
* The optional parameter can be used to specify how to calculate the size
* in a lazy fashion (see Enumerator#size). It can either be a value or
* a callable object.
*
* In the second, deprecated, form, a generated Enumerator iterates over the
* given object using the given method with the given arguments passed.
*
* Use of this form is discouraged. Use Kernel#enum_for or Kernel#to_enum
* instead.
*
* e = Enumerator.new(ObjectSpace, :each_object)
* #-> ObjectSpace.enum_for(:each_object)
*
* e.select { |obj| obj.is_a?(Class) } #=> array of all classes
*
*/