在Ruby中计算哈希值

时间:2012-09-27 15:57:03

标签: ruby

我在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有一种简单的方法吗?

2 个答案:

答案 0 :(得分:10)

这个怎么样?

counted = Hash.new(0)
domains.each { |h| counted[h["country"]] += 1 }
counted = Hash[counted.map {|k,v| [k,v.to_s] }]

答案 1 :(得分:5)

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"}