我有一个哈希数组:
[{"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
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 块在发现重复项时运行该块;inject
没有初始的memo
将数组的第一个元素视为memo
,这在这里很好。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)