后端开发 \ Ruby \ Ruby之map、each、collect、map!、collect!揭秘

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

总点击107
简介:Ruby代码   def map_method     arr1 = [\"name2\",\"class2\"]     arr2 = arr1.map {|num| num + \"and\"}  

Ruby代码  

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

def map_method  

  arr1 = ["name2","class2"]  

  arr2 = arr1.map {|num| num + "and"}  

  print "map............",arr2,"n"  

end  

  

def each_method  

  arr1 = ["name2","class2"]  

  arr2 = arr1.each {|num| num + "and"}  

  print "each............","n"  

end  

  

def collect_method  

  arr1 = ["name2","class2"]  

  arr2 = arr1.collect {|num| num + "and"}  

  print "collect............","n"  

end  

  

def map1_method  

  arr1 = ["name2","class2"]  

  arr2 = arr1.map! {|num| num + "and"}  

  print "map!............","n"  

end  

  

def collect1_method  

  arr1 = ["name2","class2"]  

  arr2 = arr1.collect! {|num| num + "and"}  

  print "collect!............","n"  

end  

  

def test  

  map_method  

  each_method  

  collect_method  

  map1_method  

  collect1_method  

end  

  

test  


result: 


map............["name2and","class2and"] 


each............["name2","class2"] 


collect............["name2and","class2and"] 


map!............["name2and","class2and"] 


collect!............["name2and","class2and"] 


为了更明了的了解each的用法,看下面的例子: 


Ruby代码  

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

def each_deep_method  

  arr_test = [1,2,3]  

  arr_result = arr_test.each do |num|  

    num = num + 1  

    p num  

  end  

  arr_result  

end  


result: 





=> [1,3] 


可见each_deep_method的返回值arr_result是和arr_test相等的。 


[总结] 


(1)each只是遍历数组的每个元素,并不生成新的数组; 


(2)map和collect相同用法,遍历每个元素,用处理之后的元素组成新的数组,并将新数组返回; 


(3)map!同collect! 


其中map和map!、collect和collect!的区别就不用纠结了吧,实在纠结就看下面的例子: 


Ruby代码  

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

def map_deep_method  

  arr_test = [1,3]  

  arr_test.map do |num|  

    num += 1  

  end  

  arr_test  #[1, 2, 3]  

end  

  

def map1_deep_method  

  arr_test = [1,3]  

  arr_test.map! do |num|  

    num += 2   

  end  

  arr_test  #[3, 4, 5]  

end  

意见反馈 常见问题 官方微信 返回顶部