简体   繁体   中英

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| 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 ". If your array contains three elements, the array will be printed three times.

This is valid ruby, but incorrect usage of each . It's supposed to accept current element in the block parameter (the |a| ). Doesn't have to be called a , can be anything. 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 . 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. 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. Really bad style. It is equivalent to

a.each {|goofy| puts goofy}

and hence you see each array element only once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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