【发布时间】:2016-08-25 04:11:36
【问题描述】:
class MyString
include Enumerable
def initialize(n)
@num = n
end
def each
i = 0
while i < @num
yield "#{i} within while"
puts "After yield #{i}"
i += 1
end
end
end
s = MyString.new(10)
a = s.to_enum
puts "first"
puts a.next
puts "second"
puts a.next
我的 ruby 版本是 2.2.5,代码输出是
第一
0 以内
第二
产后0
1 以内
我认为执行流程是first a.next->s.each->while->yield->second a.next->jump into while loop
我的问题是 Enumerator#next 方法是如何实现的?
我可能知道调用的块 yield 中有中断,这导致 yield->second a.next;但是,我不明白第二个 a.next 是如何跳回 while 循环的。
【问题讨论】:
-
我猜让你感到困惑的是
yield关键字,而不是next是如何实现的。 -
@halfelf:我相信这与
Enumerator有很大关系:在引入光纤之前,这在 1.8 中是不可能的。 Plainyield仅适用于块,并且 OP 的代码中没有块。这意味着捕获tield的块在Enumerator内部。
标签: ruby