I have an array of hashed in Ruby that looks like this:
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"}
]
From this array of hashes I want to create a new hash the looks something like this:
counted = {
"Germany" => "3",
"United Kingdom" => "United Kingdom",
"Hungary" => "3",
"United States" => "4",
"France" => "1"
}
Is there an easy way to do this using Ruby 1.9?
To find a hash key by it's value, i.e. reverse lookup, one can use Hash#key . It's available in Ruby 1.9+.
When we say a Hash is empty, what we mean is that the Hash has no entries. We can use the empty? method to check if a Hash has no entries. This method returns a Boolean, which indicates whether the Hash is empty or not.
Overview. We can check if a particular hash contains a particular key by using the method has_key?(key) . It returns true or false depending on whether the key exists in the hash or not.
In Ruby, the values in a hash can be accessed using bracket notation. After the hash name, type the key in square brackets in order to access the value.
How about this?
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"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With