我有一个哈希数组:
[{"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)
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