简体   繁体   English

{put a}和{| a |之间的差异 在Ruby中放一个}?

[英]Difference between {puts a} and {|a| puts a} in Ruby?

While I on a Ruby tutorial, i saw them use the second method of printing the whole list, |a| 在阅读Ruby教程时,我看到他们使用第二种打印整个列表的方法| a |。 puts a, but i was wondering why they didn't simply type puts a , and trying it for myself, using puts a prints the list twice and i haven't found why 放一个,但我想知道为什么他们不简单地输入一个放一个 ,然后自己尝试一下,使用两次将列表打印一次,而我还没有找到原因

irb(main):001:0> a = ['hello', 'hi']
=> ["hello", "hi"]
irb(main):002:0> a.each {puts a}
hello
hi
hello
hi
=> ["hello", "hi"]
irb(main):03:0> a.each {|a| puts a}
hello
hi
=> ["hello", "hi"]

Basically, what's the difference between these two. 基本上,两者之间有什么区别。 thanks in advance, and sorry if I'm being a doof 在此先感谢,如果我做傻了,对不起

a.each {puts a}

This means "for each element in array a , print array a ". 这意味着“对于数组a每个元素,打印数组a ”。 If your array contains three elements, the array will be printed three times. 如果您的数组包含三个元素,则该数组将被打印3次。

This is valid ruby, but incorrect usage of each . 这是有效的红宝石,但each用法都不正确。 It's supposed to accept current element in the block parameter (the |a| ). 应该在block参数( |a| )中接受当前元素。 Doesn't have to be called a , can be anything. 不必被称为a ,可以是任何东西。 These lines produce identical results: 这些行产生相同的结果:

a.each { |a| puts a }
a.each { |foo| puts foo }

In the first line block parameter a shadows outer array a . 在第一个行块参数中, a遮蔽了外部数组a That's why two elements of the array are printed instead of the whole array being printed two times. 这就是为什么打印数组的两个元素而不是打印整个数组两次的原因。

a.each {puts a}

will return the entire array 将返回整个数组

while

a.each {|a| puts a}

is supposed to pass between || 应该在||之间传递 each item of the array. 数组的每个项目。 It's actually a bad practice to use the same variable in this case. 在这种情况下,使用相同的变量实际上是一个坏习惯。 Better do: 最好做:

a.each {|item| puts item}

@ThePanMan321 : The block is executed once for each array element. @ ThePanMan321:该块对每个数组元素执行一次。 Hence in your case, it is executed twice. 因此,在您的情况下,它执行两次。 So the first case is equivalent to 所以第一种情况相当于

a.size.times {puts a}

, you get twice the array being printed. ,您将获得两倍于要打印的数组。

In the second case, the second a is shadowing the outer a denoting the array. 在第二种情况下,第二个a 遮盖 a表示数组的外部a Really bad style. 真的很糟糕。 It is equivalent to 相当于

a.each {|goofy| puts goofy}

and hence you see each array element only once. 因此,每个数组元素只能看到一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM