我有一系列散列:
[{"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