each —— 连续访问集合的所有元素,并不生成新的数组;原集合本身不会发生变化
collect —— 从集合中获得各个元素传递给block,block返回的结果生成新的集合。原集合发生变化
map —— 同collect。
2) arr2 = arr.map{|element| element = element* 2} #arr等于[1,2,3] arr2等于[2,4,6] map返回更改后的数组 遍历内对元素的更改不会保存
3) arr2 = arr.map!{|element| element = element * 2} #arr与arr2都等于[2,4,6] map!返回更改后的数组 遍历对元素内的更改会保存
collect —— 从集合中获得各个元素传递给block,block返回的结果生成新的集合。原集合发生变化
map —— 同collect。
inject —— 遍历整个集合中的各个元素,将各个元素,按照一定的方式累积,最后返回一个新的元素。原集合本身不会发生变化
map! 和 collect! 一样,返回更改后的数组 遍历对元素内的更改会保存
h = [1,2,3,4,5]
h1 = h
h1.each{|v| puts sprintf('values is : %s' ,v)}
h2 = h.collect{|x| [x,x*2]}
h2 = h.map{|x| [x,x*2]}
h2 = h.collect{|x| [x,x*2]}
h2 = h.map{|x| x*2}
h2 = h.collect{|x| x*2}
错误实例:each 循环的话,原集合不发生变化,所以x*2 没有达到需求
h4 = h.inject{|sum,item| sum+item}
names = %w[ruby rails java python cookoo firebody]
等同于:
names = ["ruby", "rails", "java", "python", "cookoo", "firebody"]
arr = [1,2,3]
1) arr2 = arr.each{|element| element = element * 2} #arr与arr2仍然都等于[1,2,3] each返回原数组 遍历内对元素的更改不会保存2) arr2 = arr.map{|element| element = element* 2} #arr等于[1,2,3] arr2等于[2,4,6] map返回更改后的数组 遍历内对元素的更改不会保存
3) arr2 = arr.map!{|element| element = element * 2} #arr与arr2都等于[2,4,6] map!返回更改后的数组 遍历对元素内的更改会保存
collect 效果等于 map
collect! 效果等于map!
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