Iterating over a hash for a key or value

You already learned how to iterate through a hash in one of our previous sections, however, it's a very critical task that you'll be using quite often. With that in mind, I'm going to 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 previous section:

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

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

people.each_key do |key| 
puts key
end

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

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:

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.16.23