Ruby中的枚举器块执行顺序

kst*_*tis 5 ruby

在David Black的The Well-Grounded Rubyist中,我遇到了以下关于枚举器的Ruby代码:

e = Enumerator.new do |y|
    puts "Starting up the block!"
    (1..3).each {|i| y << i }
    puts "Exiting the block!" 
end

p e.to_a
Run Code Online (Sandbox Code Playgroud)

返回以下输出:

Starting up the block!
Exiting the block!
[1, 2, 3]
Run Code Online (Sandbox Code Playgroud)

让我困扰的是,我无法围绕执行的顺序.我相信输出应该更直接:

Starting up the block!
[1, 2, 3]
Exiting the block!
Run Code Online (Sandbox Code Playgroud)

任何帮助将非常感激.

Mar*_*jaš 1

您对这个输出感到惊讶。

Starting up the block!
Exiting the block!
[1, 2, 3]
Run Code Online (Sandbox Code Playgroud)

这很简单。评论将说明发生了什么。

e = Enumerator.new do |y|
    # print first message
    puts "Starting up the block!"

    # append elements to array y (but don't print it)
    (1..3).each {|i| y << i }

    # print second message
    puts "Exiting the block!" 
end

# print the array
p e.to_a
Run Code Online (Sandbox Code Playgroud)