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]
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?
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 }