首页 > 解决方案 > 如何根据 ruby​​ 中的类型和名称键找到总和?(红宝石哈希数组)

问题描述

如何根据 ruby​​ 中的类型和名称键找到总和?(红宝石哈希数组)

eatables = [{type: "fruit", name: "apple", count: 2},
            {type: "vegetable", name: "pumpkin", count: 3},
            {type: 'fruit', name: 'apple', count: 1},
            {type: "vegetable", name: "pumpkin", count: 2}]

期望的输出

[{type: "fruit", name: "apple", count: 3},
 {type: "vegetable", name: "pumpkin", count: 5}]

标签: ruby-on-railsrubyruby-on-rails-5

解决方案


eatables.group_by { |h| h.slice(:name, :type) }
        .map { |key, grouped| key.merge(count: grouped.sum{ |h| h[:count] }) }

第一个操作根据名称和类型将数组拆分为组。

{{:name=>"apple", :type=>"fruit"}=>[{:type=>"fruit", :name=>"apple", :count=>2}, {:type=>"fruit", :name=>"apple", :count=>1}], {:name=>"pumpkin", :type=>"vegetable"}=>[{:type=>"vegetable", :name=>"pumpkin", :count=>3}, {:type=>"vegetable", :name=>"pumpkin", :count=>2}]}

然后,我们映射该哈希并返回一个哈希数组,其中包含输出的类型、名称和总和:

=> [{:name=>"apple", :type=>"fruit", :count=>3}, {:name=>"pumpkin", :type=>"vegetable", :count=>5}]

推荐阅读