ruby map、each 和 collect 之间有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9429034/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the difference between map, each, and collect?
提问by Rahul
In Ruby, is there any difference between the functionalities of each, map, and collect?
在 Ruby 中each,map、 和的功能之间有什么区别collect吗?
回答by Chowlett
eachis different from mapand collect, but mapand collectare the same (technically mapis an alias for collect, but in my experience mapis used a lot more frequently).
each与mapand不同collect,但mapandcollect是相同的(技术上map是 的别名collect,但在我的经验map中使用频率更高)。
eachperforms the enclosed block for each element in the (Enumerable) receiver:
each为 ( Enumerable) 接收器中的每个元素执行封闭块:
[1,2,3,4].each {|n| puts n*2}
# Outputs:
# 2
# 4
# 6
# 8
mapand collectproduce a new Arraycontaining the results of the block applied to each element of the receiver:
map并collect生成一个新的Array包含应用于接收器的每个元素的块的结果:
[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:
还有map!/collect!定义在Arrays 上;他们就地修改接收器:
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]"
回答by RubyMiner
Eachwill evaluate the block but throws away the result of Eachblock's evaluation and returns the original array.
Each将评估块但丢弃Each块的评估结果并返回原始数组。
irb(main):> [1,2,3].each {|x| x*2}
=> [1, 2, 3]
Map/collectreturn an array constructed as the result of calling the block for each item in the array.
Map/collect返回作为为数组中的每个项目调用块的结果构造的数组。
irb(main):> [1,2,3].collect {|x| x*2}
=> [2, 4, 6]

