在Ruby中,each、map和collect的功能有什么不同吗
发布于 2012-02-24 18:25:51
each不同于map和collect,但map和collect是相同的(从技术上讲,map是collect的别名,但根据我的经验,map的使用频率要高得多)。
each为(Enumerable)接收器中的每个元素执行封闭的块:
[1,2,3,4].each {|n| puts n*2}
# Outputs:
# 2
# 4
# 6
# 8map和collect生成一个新的Array,其中包含应用于接收器的每个元素的块的结果:
[1,2,3,4].map {|n| n*2}
# => [2,4,6,8]还有定义在Array上的map! / collect!;它们在适当的地方修改接收器:
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]"https://stackoverflow.com/questions/9429034
复制相似问题