【发布时间】:2020-10-21 10:18:48
【问题描述】:
我是一名经验丰富的开发人员,但也是一名 Ruby 新手。我正在阅读这个线程do..end vs curly braces for blocks in Ruby 并学到了一些关于何时使用大括号以及何时使用do .. end 块的好东西。提示之一是当您遇到副作用时使用 do .. end,当您担心返回值时使用 {}。因此,我正在尝试使用枚举器教程中的一些示例:
irb(main):001:0> my_array = [1, 2]
=> [1, 2]
irb(main):002:0> my_array.each {|num| num *= 2; puts "The new number is #{num}."}
The new number is 2.
The new number is 4.
=> [1, 2]
irb(main):003:0> my_array.each do |num| num *= 2; puts "The new number is #{num}." end
The new number is 2.
The new number is 4.
=> [1, 2]
等一下。我认为do..end 块返回一个枚举器对象?它看起来像一个数组。让我们检查一下:
irb(main):004:0> puts my_array.each {|num| num *= 2; puts "The new number is #{num}."}
The new number is 2.
The new number is 4.
1
2
=> nil
irb(main):005:0> puts my_array.each do |num| num *= 2; puts "The new number is #{num}." end
#<Enumerator:0x000055967e53ac40>
=> nil
好的,它是一个枚举器。但是在第 005 行的循环中,puts 调用的输出发生了什么变化? {} 具有预期的副作用,但 do..end 块没有,这似乎违反了该经验法则。
我的"The new number is #{num}." 字符串发生了什么事?
【问题讨论】:
-
this 回答你的问题了吗?
-
它解释了第一部分,我可能应该把它排除在我的问题之外,因为我想我明白了。但我更关心
puts "The new number is #{num}."的输出去了哪里。
标签: ruby