"1.0", "country"=>"UK"} 计算任何键中每个单独值的最佳实践/有效方法是什么?所以我可能想弄清楚有多少记录有-6ren">
gpt4 book ai didi

ruby-on-rails - rails : best practice to count key values in hash

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

我有一个用户模型,它有一个带有散列的元列,例如 {"version"=>"1.0", "country"=>"UK"}

计算任何键中每个单独值的最佳实践/有效方法是什么?所以我可能想弄清楚有多少记录有 country = UK 或 USA 或 France 等。我事先不知道每个键中的所有可能值......

我想我可以在一个大循环中做到这一点

User.all.each do |user|
user.meta["country"] ..........

但是有更好的方法吗?

最佳答案

是的,有group_by

arr = [{"version" => "1.0", "country" => "UK"},
{"version" => "1.0", "country" => "France"},
{"version" => "1.0", "country" => "UK"},
{"version" => "1.0", "country" => "USA"},
{"version" => "1.0", "country" => "France"},
{"version" => "1.0", "country" => "UK"}]
grouped = arr.group_by {|el| el["country"]}
#=> {"UK"=>[{"version"=>"1.0", "country"=>"UK"},
# {"version"=>"1.0", "country"=>"UK"},
# {"version"=>"1.0", "country"=>"UK"}],
# "France"=>[{"version"=>"1.0", "country"=>"France"},
# {"version"=>"1.0", "country"=>"France"}],
# "USA"=>[{"version"=>"1.0", "country"=>"USA"}]}
grouped.map {|k,v| [k, v.length]}
# => [["UK", 3], ["France", 2], ["USA", 1]]

关于ruby-on-rails - rails : best practice to count key values in hash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10634784/

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