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 回答