Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are array.each and array.map different? [duplicate]

Tags:

iterator

ruby

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"] 
like image 505
Jeremy Smith Avatar asked Apr 16 '11 19:04

Jeremy Smith


People also ask

What is the difference between array map and array each?

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.

What is the difference between the array forEach () and array map () methods?

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.

What is the difference between map and array?

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.

Does array map change the original array?

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.


1 Answers

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.

like image 153
DigitalRoss Avatar answered Sep 18 '22 18:09

DigitalRoss