Iterating Over a Hash for a Key or Value in Ruby
We have already learned how to iterate through a hash in one of our previous lessons, however it's a very critical task that you'll be using quite often, so I'm going to go discuss how it works in more detail. Also, I'm going to show you how you can iterate over just a key or a value.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

We have already learned how to iterate through a hash in one of our previous lessons, however it's a very critical task that you'll be using quite often. With that in mind I'm going to go discuss how it works in more detail. Also, I'm going to show you how you can iterate over only the keys or values.

I'm going to start with the hash we created in the last lesson, which is:

people = { jordan: 32, tiffany: 27, kristine: 10, heather: 29 }

When you want to only grab the keys, your code can be:

people.each_key do |key|
  puts key
end

If I run this code, it prints out each one of the keys like this:

large

Now, to iterate through the values we can leverage the each_value iterator method, like this:

people.each_value do |value|
  puts value
end

This will print out the values, which in this case, are the ages of people in the hash.

large

These built-in methods make it easy to isolate the elements that you really care about grabbing from a hash, instead of being forced to iterate over both keys and values.