Ruby之map、each、collect、map!、collect!揭秘

来源:互联网 发布:三拼域名 不值钱 编辑:程序博客网 时间:2024/05/16 18:23
Ruby代码  收藏代码
  1. def map_method  
  2.   arr1 = ["name2","class2"]  
  3.   arr2 = arr1.map {|num| num + "and"}  
  4.   print "map............",arr2,"\n"  
  5. end  
  6.   
  7. def each_method  
  8.   arr1 = ["name2","class2"]  
  9.   arr2 = arr1.each {|num| num + "and"}  
  10.   print "each............",arr2,"\n"  
  11. end  
  12.   
  13. def collect_method  
  14.   arr1 = ["name2","class2"]  
  15.   arr2 = arr1.collect {|num| num + "and"}  
  16.   print "collect............",arr2,"\n"  
  17. end  
  18.   
  19. def map1_method  
  20.   arr1 = ["name2","class2"]  
  21.   arr2 = arr1.map! {|num| num + "and"}  
  22.   print "map!............",arr2,"\n"  
  23. end  
  24.   
  25. def collect1_method  
  26.   arr1 = ["name2","class2"]  
  27.   arr2 = arr1.collect! {|num| num + "and"}  
  28.   print "collect!............",arr2,"\n"  
  29. end  
  30.   
  31. def test  
  32.   map_method  
  33.   each_method  
  34.   collect_method  
  35.   map1_method  
  36.   collect1_method  
  37. end  
  38.   
  39. test  


result: 
map............["name2and", "class2and"] 
each............["name2", "class2"] 
collect............["name2and", "class2and"] 
map!............["name2and", "class2and"] 
collect!............["name2and", "class2and"] 

为了更明了的了解each的用法,看下面的例子: 
Ruby代码  收藏代码
  1. def each_deep_method  
  2.   arr_test = [1,2,3]  
  3.   arr_result = arr_test.each do |num|  
  4.     num = num + 1  
  5.     p num  
  6.   end  
  7.   arr_result  
  8. end  

result: 



=> [1, 2, 3] 
可见each_deep_method的返回值arr_result是和arr_test相等的。 
[总结] 
(1)each只是遍历数组的每个元素,并不生成新的数组; 
(2)map和collect相同用法,遍历每个元素,用处理之后的元素组成新的数组,并将新数组返回; 
(3)map!同collect! 
其中map和map!、collect和collect!的区别就不用纠结了吧,实在纠结就看下面的例子: 
Ruby代码  收藏代码
  1. def map_deep_method  
  2.   arr_test = [1,2,3]  
  3.   arr_test.map do |num|  
  4.     num += 1  
  5.   end  
  6.   arr_test  #[1, 2, 3]  
  7. end  
  8.   
  9. def map1_deep_method  
  10.   arr_test = [1,2,3]  
  11.   arr_test.map! do |num|  
  12.     num += 2   
  13.   end  
  14.   arr_test  #[3, 4, 5]  
  15. end  
原创粉丝点击