Array#each vs. Array#map

user612308 picture user612308 · Mar 10, 2011 · Viewed 49.7k times · Source
hash = { "d" => [11, 22], "f" => [33, 44, 55] }

# case 1
hash.map {|k,vs| vs.map {|v| "#{k}:#{v}"}}.join(",")
=> "d:11,d:22,f:33,f:44,f:55"

# case 2
hash.map {|k,vs| vs.each {|v| "#{k}:#{v}"}}.join(",")
=> "11,22,33,44,55"

only difference is case 1 uses vs.map, case 2 uses vs.each.

What happened here?

Answer

Olives picture Olives · Mar 10, 2011

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"]