加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby中的枚举器块执行顺序

发布时间:2020-12-17 03:25:11 所属栏目:百科 来源:网络整理
导读:在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!" endp e.to_a 返回以下输出: Starting up the block!Exitin
在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

返回以下输出:

Starting up the block!
Exiting the block!
[1,2,3]

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

Starting up the block!
[1,3]
Exiting the block!

任何帮助将非常感激.

解决方法

你对这个输出感到惊讶.

Starting up the block!
Exiting the block!
[1,3]

这很简单.评论将说明正在发生的事情.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读