How to count Ruby Array items

You’re closer than you think to a career in tech. Our grads have launched rewarding new careers — you can too.

View Our Jobs Report

The following is a guest post by Rex Feng and originally appeared on his blog. Rex is currently a student a The Flatiron School. You can learn more about him here, or follow him on twitter here.

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 animals that we want to count.

Blog post image: tumblr_mexmq5stvj1rtan47.png

We can count them up by creating a new Hash.

Blog post image: tumblr_mexmqcXYNe1rtan47.png

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

Blog post image: tumblr_mexmqnoHuU1rtan47.png

For each animal in animals, we’ve either created a new Key / Value pair in animal_count or incremented the Value corresponding to the animal Key.

Blog post image: tumblr_mexmqyuB5k1rtan47.png

Headshot of Flatiron School

Flatiron School

Blog Post Author

Read More Flatiron School Articles

Since we opened our doors in 2012, thousands of students have joined Flatiron School to launch new careers in tech.

Explore our Courses

Find the perfect course for you across our in-person and online programs designed to power your career change.

Explore Our Courses
Join a Community

Connect with students and staff at meetups, lectures, and demos – on campus and online.

Join the Community
Schedule a Chat

Have a question about our programs? Our admissions team is here to help.

Schedule a Chat