ThePanMan321
ThePanMan321

Reputation: 13

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

Upvotes: 1

Views: 115

Answers (3)

user1934428
user1934428

Reputation: 22366

@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.

Upvotes: 0

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230561

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.

Upvotes: 4

Jean Meyer
Jean Meyer

Reputation: 409

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}

Upvotes: 0

Related Questions