Tag Archives: iterate

How to count Ruby Array items

While working in Ruby, I often find myself trying to get a count of the number of times each item appears in an array. Below, I’ll show you how to create a Hash that iterates through each item in the array and counts the number of occurrences.

We have an array of [cci]animals[/cci] that we want to count.

[cc]animals = [“tiger”,
“tiger”,
“lion”,
“dog”,
“cat”,
“mouse”,
“bear”,
“frog”,
“tiger”,
“lion”,
“frog”,
“fish”,
“cat”,
“dog”,
“cat”
][/cc]
We can count them up by creating a new Hash.

[cc]animal_count = Hash.new(0)[/cc]

Next, we want to iterate through the [cci]animals[/cci] Array and set the [cci]animal_count[/cci] Key as the animal name & the [cci]animal_count[/cci] Value as the counter.

[cc]animals.each { |animal| animal_count[animal] += 1 }[/cc]

For each [cci]animal[/cci] in [cci]animals[/cci], we’ve either created a new Key / Value pair in [cci]animal_count[/cci] or incremented the Value corresponding to the [cci]animal[/cci] Key.
[cc]puts animal_count
#=> {“tiger”=>3, “lion”=>2, “dog”=>2, “cat”=>3, “mouse”=>1, “bear”=>1, “frog”=>2, “fish”=>1} [/cc]