按键对散列进行分组并对值求和
我有一个哈希数组:
[{"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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
只需使用:
Simply use:
虽然
Hash.merge
技术工作得很好,但我认为使用inject
读起来更好:如果您将
Hash.new
与默认值 0:或者如果
inject
让你头疼:While the
Hash.merge
technique works fine, I think it reads better with aninject
:Better yet, if you use
Hash.new
with a default value of 0:Or if
inject
makes your head hurt:我不确定这里的哈希是您想要的,因为我不在每个哈希中包含多个条目。所以我将从稍微改变你的数据表示开始。
如果哈希可以有多个键值对,那么您可能想要做的是
现在使用facet gem,如下所示
结果是
I'm not sure that a hash is what you want here, because I don't multiple entries in each hash. so I'll start by changing your data representation a little.
If the hashes can have multiple key-value pairs, then what you probably want to do is
Now use the facets gem as follows
The result is
如果有两个具有多个键的哈希值:
If have two hashes with multiple keys:
带有块的
Hash.merge
在发现重复项时运行该块;没有初始memo
的inject
将数组的第一个元素视为memo
,这在这里很好。Hash.merge
with a block runs the block when it finds a duplicate;inject
without a initialmemo
treats the first element of the array asmemo
, which is fine here.