Rails: best practice to count key values in hash
ruby, ruby-on-rails, ruby-on-rails-3
Solution
Yes, there's `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]]
Problem
I have a User model that has a meta column with a hash, for example {"version"=>"1.0", "country"=>"UK"} What is the best practice / efficient way to count each individual values in any key? So I might want to figure out how many records have country = UK or USA or France, etc. I do not know all the possible values in each key beforehand... I guess I can do it in a big loop ``` User.all.each do |user| user.meta["country"] .......... ``` but is there a better way to do it?