Question
This question already has answers here :
[what's different between each and collect method in Ruby [duplicate]](/questions/5347949/whats-different-between-each-and-collect- method-in-ruby) (7 answers)
Closed 9 years ago.
In Ruby, is there any difference between the functionalities of each
, map
,
and collect
?
Answer
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]"