Array#each
executes the given block for each element of the array, then returns the array itself.
Array#map
also executes the given block for each element of the array, but returns a new array whose values are the return values of each iteration of the block.
Example: assume you have an array defined thusly:
arr = ["tokyo", "london", "rio"]
Then try executing each
:
arr.each { |element| element.capitalize }
# => ["tokyo", "london", "rio"]
Note the return value is simply the same array. The code inside the each
block gets executed, but the calculated values are not returned; and as the code has no side effects, this example performs no useful work.
In contrast, calling the array’s map
method returns a new array whose elements are the return values of each round of executing the map
block:
arr.map { |element| element.capitalize }
# => ["Tokyo", "London", "Rio"]