13

次のようなRubyのハッシュ配列があります。

domains = [
  { "country" => "Germany"},
  {"country" => "United Kingdom"},
  {"country" => "Hungary"},
  {"country" => "United States"},
  {"country" => "France"},
  {"country" => "Germany"},
  {"country" => "Slovakia"},
  {"country" => "Hungary"},
  {"country" => "United States"},
  {"country" => "Norway"},
  {"country" => "Germany"},
  {"country" => "United Kingdom"},
  {"country" => "Hungary"},
  {"country" => "United States"},
  {"country" => "Norway"}
]

このハッシュの配列から、次のような新しいハッシュを作成します。

counted = {
  "Germany" => "3",
  "United Kingdom" => "United Kingdom",
  "Hungary" => "3",
  "United States" => "4",
  "France" => "1"
}

Ruby 1.9を使用してこれを行う簡単な方法はありますか?

4

2 に答える 2

13

これはどう?

counted = Hash.new(0)
domains.each { |h| counted[h["country"]] += 1 }
counted = Hash[counted.map {|k,v| [k,v.to_s] }]
于 2012-09-27T17:31:16.103 に答える
6
domains.each_with_object(Hash.new{|h,k|h[k]='0'}) do |h,res|
  res[h['country']].succ!
end
=> {"Germany"=>"3",
 "United Kingdom"=>"2",
 "Hungary"=>"3",
 "United States"=>"3",
 "France"=>"1",
 "Slovakia"=>"1",
 "Norway"=>"2"}
于 2012-09-27T17:54:58.527 に答える