【发布时间】:2016-12-19 02:56:55
【问题描述】:
puts "Example of each"
x = [1,2,3]
a = x.each{ |i|
i+1
}
puts a.inspect
puts x.inspect
puts "Example of map"
b = x.map{ |i|
i+1
}
puts b.inspect
puts x.inspect
puts "Example of collect"
c = x.collect{ |i|
i+1
}
puts c.inspect
puts x.inspect
输出
Example of each
[1, 2, 3]
[1, 2, 3]
Example of map
[2, 3, 4]
[1, 2, 3]
Example of collect
[2, 3, 4]
[1, 2, 3]
在这里,我们看到每个块返回相同的值传递给它,而不管它内部的操作。而且地图和收集似乎是一样的。那么基本上map和collect有什么区别呢?
【问题讨论】:
-
请点击链接:rubyinrails.com/2014/01/25/… 从上面链接的解释中你会知道; 1. 在 Ruby 中,collect 和 map 之间不存在区别。 2.这些方法的C级实现表明它们都是相同的。 3. 所以,collect 是 Map 的别名。
标签: ruby