Ruby迭代器each,map,collect的区别

a=[{id:1,sum:11},{id:2,sum:22}]

语法格式:

a.each/map/inject/collect {|a| ...代码块...}

a.each/map/inject/collect do |a|

...代码块...

end


each:遍历数据a,对原数组进行处理

b=a.each do |a|

a[:sum]=11

end

b=[{id:1,sum:11},{id:2,sum:11}]

a=[{id:1,sum:11},{id:2,sum:11}]

map:遍历数据a,不对原数组进行处理,创建新数组

b=a.map do |a|

a[:sum]=11

end

b=[{id:1,sum:11},{id:2,sum:11}]

a=[{id:1,sum:11},{id:2,sum:22}]

collect:同map

你可能感兴趣的:(Ruby迭代器each,map,collect的区别)