Possible Duplicate:
Array#each vs. Array#map
ruby-1.9.2-p180 :006 > ary = ["a", "b"]
=> ["a", "b"]
ruby-1.9.2-p180 :007 > ary.map { |val| p val }
"a"
"b"
=> ["a", "b"]
ruby-1.9.2-p180 :008 > ary.each { |val| p val }
"a"
"b"
=> ["a", "b"]
ruby-1.9.2-p180 :009 > ary.map { |val| val << "2" }
=> ["a2", "b2"]
ruby-1.9.2-p180 :010 > ary.each { |val| val << "2" }
=> ["a22", "b22"]
The map method is very similar to the forEach method—it allows you to execute a function for each element of an array. But the difference is that the map method creates a new array using the return values of this function. map creates a new array by applying the callback function on each element of the source array.
The first difference between map() and forEach() is the returning value. The forEach() method returns undefined and map() returns a new array with the transformed elements. Even if they do the same job, the returning value remains different.
Map stores data in form of key : value which provides faster look ups as compared to an array. Map should be used when we have to maintain some relation between elements. eg : Count the occurrence of all the character in a given string and print key value pair for them.
map() creates a new array from calling a function for every array element. map() calls a function once for each element in an array. map() does not execute the function for empty elements. map() does not change the original array.
The side effects are the same which is adding some confusion to your reverse engineering.
Yes, both iterate over the array (actually, anything that mixes in Enumerable) but map will return an Array composed of the block results while each will just return the original Array. The return value of each is rarely used in Ruby code but map is one of the most important functional tools.
BTW, you may be having a hard time finding the documentation because map is a method in Enumerable while each (the one method required by the Enumerable module) is a method in Array.
As a trivia note: the map implementation is based on each.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With