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

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

问题描述

我有一个哈希数组:

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

我需要在这里使用 inject ,但我确实一直在挣扎。



我想要一个新的散列,它反映了以前散列重复键的总和:

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






我控制输出这个散列的代码,所以我可以根据需要修改它。结果主要是哈希,因为这可能会嵌套任意数量的层次,然后很容易在数组上调用flatten,但不会将哈希的键/值弄平:

  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)
如果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}, {蔬菜=> 5},{干货=> 3},{干货=> 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 在块中找到重复时运行该块; 注入不带初始备忘录将数组的第一个元素视为 memo ,这在这里很好。


I have an array of hashes:

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

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}]


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 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天全站免登陆