Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between map, each, and collect? [duplicate]

In Ruby, is there any difference between the functionalities of each, map, and collect?

like image 769
Rahul Avatar asked Feb 24 '12 10:02

Rahul


People also ask

What is difference between map and collect in Ruby?

There's no difference, in fact map is implemented in C as rb_ary_collect and enum_collect (eg. there is a difference between map on an array and on any other enum, but no difference between map and collect ). Why do both map and collect exist in Ruby? The map function has many naming conventions in different languages.

What is the difference between MAP and each?

The main difference between map and forEach is that the map method returns a new array by applying the callback function on each element of an array, while the forEach method doesn't return anything. You can use the forEach method to mutate the source array, but this isn't really the way it's meant to be used.

What does .collect do in Ruby?

The collect() of enumerable is an inbuilt method in Ruby returns a new array with the results of running block once for every element in enum. The object is repeated every time for each enum. In case no object is given, it return nil for each enum.

What is map in Ruby?

The map() of enumerable is an inbuilt method in Ruby returns a new array with the results of running block once for every element in enum. The object is repeated every time for each enum. In case no object is given, it return nil for each enum.


2 Answers

Each will evaluate the block but throws away the result of Each block's evaluation and returns the original array.

irb(main):> [1,2,3].each {|x| x*2} => [1, 2, 3] 

Map/collect return an array constructed as the result of calling the block for each item in the array.

irb(main):> [1,2,3].collect {|x| x*2} => [2, 4, 6] 
like image 21
RubyMiner Avatar answered Sep 22 '22 04:09

RubyMiner


each is different from map and collect, but map and collect are the same (technically map is an alias for collect, but in my experience map is used a lot more frequently).

each performs the enclosed block for each element in the (Enumerable) receiver:

[1,2,3,4].each {|n| puts n*2} # Outputs: # 2 # 4 # 6 # 8 

map and collect produce a new Array containing the results of the block applied to each element of the receiver:

[1,2,3,4].map {|n| n*2} # => [2,4,6,8] 

There's also map! / collect! defined on Arrays; they modify the receiver in place:

a = [1,2,3,4] a.map {|n| n*2} # => [2,4,6,8] puts a.inspect  # prints: "[1,2,3,4]" a.map! {|n| n+1} puts a.inspect  # prints: "[2,3,4,5]" 
like image 137
Chowlett Avatar answered Sep 26 '22 04:09

Chowlett