Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting hash values in Ruby [closed]

Tags:

ruby

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?

like image 286
user1513388 Avatar asked Sep 27 '12 15:09

user1513388


People also ask

How does Ruby calculate hash value?

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+.

How do you check if a hash is empty in Ruby?

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.

How do you check if a hash has a key Ruby?

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.

How do you access the hash in Ruby?

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.


Video Answer


2 Answers

How about this?

counted = Hash.new(0)
domains.each { |h| counted[h["country"]] += 1 }
counted = Hash[counted.map {|k,v| [k,v.to_s] }]
like image 131
Tim Destan Avatar answered Oct 09 '22 02:10

Tim Destan


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"}
like image 43
megas Avatar answered Oct 09 '22 02:10

megas