Ответ 1
Как насчет этого?
counted = Hash.new(0)
domains.each { |h| counted[h["country"]] += 1 }
counted = Hash[counted.map {|k,v| [k,v.to_s] }]
У меня есть массив хэширования в 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?
Как насчет этого?
counted = Hash.new(0)
domains.each { |h| counted[h["country"]] += 1 }
counted = Hash[counted.map {|k,v| [k,v.to_s] }]
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"}