我在
Ruby中有一个散列数组,如下所示:
domains = [ { "country" => "Germany"},{"country" => "United Kingdom"},{"country" => "Hungary"},{"country" => "United States"},{"country" => "France"},{"country" => "Germany"},{"country" => "Slovakia"},{"country" => "Norway"},{"country" => "Norway"} ]
从这个散列数组我想创建一个新的哈希看起来像这样:
counted = { "Germany" => "3","United Kingdom" => "United Kingdom","Hungary" => "3","United States" => "4","France" => "1" }
有没有一个简单的方法来做这个使用Ruby 1.9?
解决方法
这个怎么样?
counted = Hash.new(0) domains.each { |h| counted[h["country"]] += 1 } counted = Hash[counted.map {|k,v| [k,v.to_s] }]