-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的別名。 –