reduce and each_with_object

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}

 

posted @ 2016-02-24 10:16  耿小曾  阅读(126)  评论(0编辑  收藏  举报