首页 > 其他 > 详细

reduce and each_with_object

时间:2016-02-24 10:44:40      阅读:237      评论:0      收藏:0      [点我收藏+]
target = [{material: legend, quantity: 5}, {material: angel, quantity: 10}, {material: angel, quantity: 5}]
target.each_with_object(Hash.new(0)) do |value, hash|
  hash[value[:material]] += value[:quantity].to_i
end # {"legend"=>5, "angel"=>15}

target = [{material: legend, quantity: 5}, {material: angel, quantity: 10}, {material: angel, quantity: 5}]
target.reduce(Hash.new(0)) do |hash, value|
  hash[value[:material]] += value[:quantity].to_i
  hash
end # {"legend"=>5, "angel"=>15}

 

reduce and each_with_object

原文:http://www.cnblogs.com/angelfan/p/5211986.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!