为什么Ruby每个迭代器在执行中首先出现?

时间:2017-02-21 09:46:25

标签: ruby iteration each puts

我在Ruby中执行简单的任务时遇到了一个奇怪的事情。我只想用每个方法迭代字母表,但迭代在执行中先行:

alfawit = ("a".."z")
puts "That's an alphabet: \n\n #{ alfawit.each { |litera| puts litera } } "

并且此代码导致:(缩写)

a
b
c
⋮
x
y
z
That's an alphabet: 

 a..z 

为什么它会像这样或者我认为我做错了什么?

提前致谢。

2 个答案:

答案 0 :(得分:5)

因为您的each调用是在字符串文字中插入的,而这些调用是在固定字符串之前执行的。另外,each会返回Enumerable,实际上您甚至会打印出来。试试这个

alfawit = ("a".."z")
puts "That's an alphabet: \n\n"
alfawit.each { |litera| puts litera } 

puts "That's an alphabet: \n\n"
("a".."z").each { |litera| puts litera } 

如果你愿意,你可以使用插值

alfawit = ("a".."z")
puts "That's an alphabet: \n\n#{alfawit.to_a.join("\n")}"

答案 1 :(得分:3)

如果将插值部分提取到变量中,您可以很容易地看到正在发生的事情:

alfawit = ("a".."z")
foo = alfawit.each { |litera| puts litera }
puts "That's an alphabet: \n\n #{ foo } "

第二行导致问题:each为范围的每个元素调用块,然后返回接收者,以便foo变为alfawit

这是获得理想结果的另一种方法:

alfawit = "a".."z"
puts "That's an alphabet:", alfawit.to_a

puts在新行上输出每个参数,但对于数组参数,它会在新行上输出每个元素。结果:

That's an alphabet:
a
b
c
⋮
x
y
z

同样,您可以通过*

将范围转换为argument list
alfawit = "a".."z"
puts "That's an alphabet:", *alfawit

这相当于:

puts "That's an alphabet:", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"