Why does Array#each return an array with the same elements?

Jeff Storey picture Jeff Storey · Jul 22, 2012 · Viewed 17.6k times · Source

I'm learning the details of how each works in ruby, and I tried out the following line of code:

p [1,2,3,4,5].each { |element| el }

And the result is an array of

[1,2,3,4,5]

But I don't think I fully understand why. Why is the return value of each the same array? Doesn't each just provide a method for iterating? Or is it just common practice for the each method to return the original value?

Answer

user166390 picture user166390 · Jul 22, 2012

Array#each returns the [array] object it was invoked upon: the result of the block is discarded. Thus if there are no icky side-effects to the original array then nothing will have changed.

Perhaps you mean to use map?

p [1,2,3,4,5].map { |i| i*i }