You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby中如何按type和name键对哈希数组的count字段分组求和

Ruby 哈希数组按多字段分组累加实现方案

核心实现逻辑:先将数组元素按照type和name两个字段组合成的唯一键分组,再对每个分组内的所有count值求和,最后重新组装为目标结构的哈希数组即可。

完整可运行代码(兼容Ruby 2.4及以上版本)

# 示例输入
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}]

# 核心处理逻辑
result = eatables.group_by { |item| [item[:type], item[:name]] }
                 .map do |(type, name), group_items|
                   {
                     type: type,
                     name: name,
                     count: group_items.sum { |i| i[:count] }
                   }
                 end

# 验证输出
p result
# 输出结果:
# [{:type=>"fruit", :name=>"apple", :count=>3}, {:type=>"vegetable", :name=>"pumpkin", :count=>5}]

低版本Ruby兼容写法

如果使用的是Ruby 2.4以下的版本,原生不支持sum方法,可以将求和逻辑替换为inject实现:

count: group_items.inject(0) { |sum, i| sum + i[:count] }

内容的提问来源于stack exchange,提问作者alavni shubham

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 18:36:03