按键对散列进行分组并对值求和 [英] Group hashes by keys and sum the values

查看:41
本文介绍了按键对散列进行分组并对值求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个哈希数组:

[{"Vegetable"=>10}, {"Vegetable"=>5}, {"Dry Goods"=>3>}, {"Dry Goods"=>2}]

我想在这里我需要使用 inject,但我真的很挣扎.

I need to use inject here I think but I've really been struggling.

我想要一个反映前一个哈希重复键总和的新哈希:

I want a new hash that reflects the sum of the previous hash's duplicate keys:

[{"Vegetable"=>15}, {"Dry Goods"=>5}]

<小时>

我控制着输出这个散列的代码,所以我可以在必要时修改它.结果主要是散列,因为这可能最终嵌套任意数量的深度,然后很容易在数组上调用 flatten 但也不能压平哈希的键/值:


I'm in control of the code that outputs this hash so I can modify it if necessary. The results were mainly hashes because this could end up nested any number of levels deep and then it's easy to call flatten on the array but not flatten the keys/values of the hash too:

def recipe_pl(parent_percentage=nil)
  ingredients.collect do |i|

    recipe_total = i.recipe.recipeable.total_cost 
    recipe_percentage = i.ingredient_cost / recipe_total

    if i.ingredientable.is_a?(Purchaseitem)
      if parent_percentage.nil?
        {i.ingredientable.plclass => recipe_percentage}
      else
        sub_percentage = recipe_percentage * parent_percentage
        {i.ingredientable.plclass => sub_percentage}
      end
    else
      i.ingredientable.recipe_pl(recipe_percentage)
    end
  end
end 

推荐答案

ar = [{"Vegetable"=>10}, {"Vegetable"=>5}, {"Dry Goods"=>3}, {"Dry Goods"=>2}]
p ar.inject{|memo, el| memo.merge( el ){|k, old_v, new_v| old_v + new_v}}
#=> {"Vegetable"=>15, "Dry Goods"=>5}

Hash.merge with a block 当它找到重复时运行该块;没有初始 memoinject 将数组的第一个元素视为 memo,这里没问题.

Hash.merge with a block runs the block when it finds a duplicate; inject without a initial memo treats the first element of the array as memo, which is fine here.

这篇关于按键对散列进行分组并对值求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆