Agrupe hashes por claves y sume los valores
Tengo una variedad de hashes:
[{"Vegetable"=>10}, {"Vegetable"=>5}, {"Dry Goods"=>3>}, {"Dry Goods"=>2}]
Necesito usarinject
aquí pienso pero realmente he estado luchando.
Quiero un nuevo hash que refleje la suma de las claves duplicadas del hash anterior:
[{"Vegetable"=>15}, {"Dry Goods"=>5}]
Tengo el control del código que genera este hash para poder modificarlo si es necesario. Los resultados fueron principalmente hashes porque esto podría terminar anidando cualquier número de niveles de profundidad y luego es fácil llamar a aplanar en la matriz pero no aplanar las claves / valores del hash también:
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