- 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............",arr2,"\n"
- end
- def collect_method
- arr1 = ["name2","class2"]
- arr2 = arr1.collect {|num| num + "and"}
- print "collect............",arr2,"\n"
- end
- def map1_method
- arr1 = ["name2","class2"]
- arr2 = arr1.map! {|num| num + "and"}
- print "map!............",arr2,"\n"
- end
- def collect1_method
- arr1 = ["name2","class2"]
- arr2 = arr1.collect! {|num| num + "and"}
- print "collect!............",arr2,"\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的用法,看下面的例子:
- 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:
2
3
4
=> [1, 2, 3]
可见each_deep_method的返回值arr_result是和arr_test相等的。
[总结]
(1)each只是遍历数组的每个元素,并不生成新的数组;
(2)map和collect相同用法,遍历每个元素,用处理之后的元素组成新的数组,并将新数组返回;
(3)map!同collect!
其中map和map!、collect和collect!的区别就不用纠结了吧,实在纠结就看下面的例子:
- def map_deep_method
- arr_test = [1,2,3]
- arr_test.map do |num|
- num += 1
- end
- arr_test #[1, 2, 3]
- end
- def map1_deep_method
- arr_test = [1,2,3]
- arr_test.map! do |num|
- num += 2
- end
- arr_test #[3, 4, 5]
- end