map、each 和 collect 之间有什么区别? [英] What is the difference between map, each, and collect?
问题描述
在 Ruby 中,each
、map
和 collect
的功能有什么区别吗?
In Ruby, is there any difference between the functionalities of each
, map
, and collect
?
推荐答案
each
与map
和collect
不同,但map
和 collect
是相同的(技术上map
是collect
的别名,但根据我的经验map
code> 的使用频率更高).
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
为 (Enumerable
) 接收器中的每个元素执行封闭块:
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
和 collect
生成一个新的 Array
包含应用于接收器的每个元素的块的结果:
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]
还有 map!
/collect!
定义在 Array
上;他们就地修改接收器:
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]"
这篇关于map、each 和 collect 之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!