在 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 的别名,但根据我的经验mapcode> 的使用频率更高).
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 # 8map 和 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 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]"更多推荐
map、each 和 collect 之间有什么区别?
发布评论