在Ruby中计算哈希值

前端之家收集整理的这篇文章主要介绍了在Ruby中计算哈希值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在 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] }]

猜你在找的Ruby相关文章