# Array＃each与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"` `

`Array#each`为数组的每个元素执行给定的块，然后返回数组本身。

`Array#map`还为数组的每个元素执行给定的块，但是返回一个新的数组，它的值是块的每个迭代的返回值。

` `arr = ["tokyo", "london", "rio"]` `

` `arr.each { |element| element.capitalize } # => ["tokyo", "london", "rio"]` `

` `arr.map { |element| element.capitalize } # => ["Tokyo", "London", "Rio"]` `

` ` 2.2.3 :001 > [:how, :now, :brown, :cow].map &:to_s => ["how", "now", "brown", "cow"]` `

` `[:how.to_s, :now.to_s, ...]` `

` `a = ["a", "b", "c"]; #Array.map p a.map {|item| "map_" + item} #prints ["map_a", "map_b", "map_c"] #Array.each p a.each {|item| "map_" + item} #prints ["a", "b", "c"]` `

`.each`返回最初提供的同一个数组：

` `[1,2,3].each { |i| i + 1 } #=> [1,2,3]` `

`.map`从每个块调用的结果中返回一个新的数组：

` `[1,2,3].map { |i| i + 1 } #=> [2,3,4]` `

` `[["d", [11, 22]], ["f", [33, 44, 55]]]` `

vs.each {…}只给出了[[d，[11,22]]和[33,44,55]的最后一个评估[11,22]中的[“f”，[ 33，44，55]]。 所以在最后join之前，你有

` `[[11, 22], [33, 44, 55]]` `

Array＃每个方法返回相同的数组

` `a = [1,2,3,4,5] a.object_id #70284994490700 b = a.each {|n| n + 2} pb #[1,2,3,4,5] b.object_id #70284994490700 <<--- it's the same as a` `

Array＃map方法返回一个新的数组

` `c = [1,2,3,4,5] c.object_id #70219117705860 d = c.map {|n| n + 2} pd #[3,4,5,6,7] d.object_id #70284994343620 <<---- it's different than c` `