相关疑难解决方法(0)

按键分组并对值求和

我有一系列哈希:

[{"Vegetable"=>10}, {"Vegetable"=>5}, {"Dry Goods"=>3>}, {"Dry Goods"=>2}]
Run Code Online (Sandbox Code Playgroud)

我需要在inject这里使用,但我确实在苦苦挣扎.

我想要一个反映前一个哈希重复键总和的新哈希:

[{"Vegetable"=>15}, {"Dry Goods"=>5}]
Run Code Online (Sandbox Code Playgroud)

我控制输出此哈希的代码,以便我可以在必要时进行修改.结果主要是哈希,因为这可能会最终嵌套任意数量的级别,然后很容易在数组上调用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 
Run Code Online (Sandbox Code Playgroud)

ruby hash key enumerable

40
推荐指数
3
解决办法
3万
查看次数

标签 统计

enumerable ×1

hash ×1

key ×1

ruby ×1