Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array#each vs. Array#map

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?

like image 956
user612308 Avatar asked Mar 10 '11 00:03

user612308


1 Answers

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"] 
like image 87
Kyle d'Oliveira Avatar answered Sep 20 '22 11:09

Kyle d'Oliveira