In Ruby, is there any difference between the functionalities of each
, map
, and collect
?
Asked
Active
Viewed 4.1k times
62

Andrew Marshall
- 95,083
- 20
- 220
- 214

Rahul
- 44,892
- 25
- 73
- 103
2 Answers
117
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 Array
s; 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]"

Chowlett
- 45,935
- 20
- 116
- 150
-
2map is the community-choosen version https://github.com/bbatsov/ruby-style-guide#map-fine-select-reduce-size – Enrico Carlesso Sep 02 '14 at 20:20
24
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]

Anshul Goyal
- 73,278
- 37
- 149
- 186

RubyMiner
- 311
- 2
- 12