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}
相關文章
相關標籤/搜索