ruby中map和collect之间有什么区别

时间:2016-08-12 07:19:52

标签: ruby

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基本上有什么区别?

1 个答案:

答案 0 :(得分:4)

绝对没有,它是别名。