6, "score"=>4, "team"=>"Challenger"}, {"point"=>4, "score"=>2, "te-6ren">
gpt4 book ai didi

ruby - 通过一些键和其他键的总和值合并哈希数组

转载 作者:数据小太阳 更新时间:2023-10-29 08:19:30 25 4
gpt4 key购买 nike

我有一个类似的数组

array = [
{"point"=>6, "score"=>4, "team"=>"Challenger"},
{"point"=>4, "score"=>2, "team"=>"INB"},
{"point"=>2, "score"=>2, "team"=>"Super-11"},
{"point"=>3, "score"=>7, "team"=>"INB"}
]

我想按“团队”合并散列并对“点”和“分数”的值求和。如果点大于 5,还想在每个散列中插入一个“合格”键。因此最终结果将是:

result= [
{"point"=>6, "score"=>4, "qualified"=> "yes", "team"=>"Challenger"},
{"point"=>7, "score"=>9, "qualified"=> "yes", "team"=>"INB"},
{"point"=>2, "score"=>2, "qualified"=> "no", "team"=>"Super-11"}
]

如有任何帮助,我们将不胜感激。谢谢!

最佳答案

另一种可能的解决方案:)

array.group_by { |item| item['team'] }.map do |_, items| 
result = items.inject({}) { |hash, item| hash.merge(item) { |_, old, new| Integer(old) + new rescue old } }
result.merge("qualified" => result['point'] > 5 ? "yes" : "no")
end

关于ruby - 通过一些键和其他键的总和值合并哈希数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51336139/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com