ruby-on-rails - 如何根据 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}]
解决方案
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}]
推荐阅读
- excel - 加入升序范围之间的所有单元格值
- javascript - 为待办事项添加任务
- scala - 如何使用 SparkContext.submitJob 调用 REST API
- javascript - Typescript动态过滤对象数组
- spring - 在 Spring MVC 应用程序的启动和关闭时创建日志记录
- regex - 规则参数 Gitlab CI 的模式匹配
- powershell - 通过使用这些 dll/exe 杀死进程来替换远程服务器上的 .dll/.exe
- javascript - 如何样式化共享同一类的元素
- react-native - 在 iOS 上禁用智能标点符号
- javascript - 使用 NodeJS 在 UI 级别对数据进行分页