The difference between Enumerable#each
and Enumerable#map
is whether it returns the receiver or the mapped result. Getting back to the receiver is
The difference between map
and each
is more important than whether one returns a new array and the other doesn't. The important difference is in how they communicate your intent.
When you use each
, your code says "I'm doing something for each element." When you use map
, your code says "I'm creating a new array by transforming each element."
So while you could use map
in place of each
, performance notwithstanding, the code would now be lying about its intent to anyone reading it.
The choice between map
or each
should be decided by the desired end result: a new array or no new array. The result of map
can be huge and/or silly:
p ("aaaa".."zzzz").map{|word| puts word} #huge and useless array of nil's
I agree with what you said. Enumerable#each
simply returns the original object it was called on while Enumerable#map
sets the current element being iterated over to the return value of the block, and then returns a new object with those changes.
Since Enumerable#each
simply returns the original object itself, it can be very well preferred over the map
when it comes to cases where you need to simply iterate or traverse over elements.
In fact, Enumerable#each
is a simple and universal way of doing a traditional iterating for loop, and each is much preferred over for loops in Ruby.
You can see the significant difference between map
and each
when you're composing these enumaratiors.
For example you need to get new array with indixes in it:
array.each.with_index.map { |index, element| [index, element] }
Or for example you just need to apply some method to all elements in array and print result without changing the original array:
m = 2.method(:+)
[1,2,3].each { |a| puts m.call(a) } #=> prints 3, 4, 5
And there's a plenty another examples where the difference between each
and map
is important key in the writing code in functional style.