-1
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]
在这里,我们看到每块返回传递给它不管里面的操作相同的值。地图和收集似乎是一样的。那么基本上地图和收集有什么区别?
有一个正确的解释http://stackoverflow.com/questions/5254732/difference-between-map-and-collect-in-ruby –
请点击链接:http://rubyinrails.com/2014/01/25/ruby-difference-between-collect-and-map/ 从上面的链接中的解释你会知道的; 1.在Ruby中,collect和map之间的区别不存在。 2.这些方法的C级实现表明它们都是相同的。所以,collect是Map的别名。 –