Iterating Through Hashes in Ruby
In my career, I have only seen Ruby hashes being iterated through by declaring both the key and value. However, there are several ways of approaching hash iterations.
Note that at the time of this writing I’m running Ruby 3.1.2.
Iterating With Key and Value
The most common way I’ve seen hash iterations is by declaring both the key and value variables in the loop. The result is as expected:
|
|
The code above has the following output:
|
|
Iterating With a Single Variable
When iterating through a hash and declaring only a single variable, the variable is an array containing the key and value of the hash as elements.
|
|
The code above has the following output:
|
|
In this case, the item
variable is an array of 2 elements. The keys are Symbols while the values retain their original type.
There is also the .each_pair
method, which works exactly the same way:
|
|
The output is exactly the same as before:
|
|
Iterating Through Keys
The keys of a Ruby hash can be retrieved with .keys
:
|
|
The code above prints out the following:
|
|
If we want to iterate over each key, we can use .keys
in a loop:
|
|
And the output is exactly the same:
|
|
Finally, there is also the .each_key
method that works the same way and is recommended by Rubocop:
|
|
Once again, the output is the same:
|
|
Iterating Through Values
Like with keys, the values of a hash can be retrieved with .values
:
|
|
The code above outputs the following:
|
|
We can use .values
to iterate through the values of a hash:
|
|
The output is the same:
|
|
There is also the .each_value
method that achieves the same result and is also recommended by Rubocop:
|
|
Once again, the output is exactly the same as before:
|
|