How To Iterate Hash In Ruby

In Ruby, a hash is a collection of key-value pairs, and it is similar to
a dictionary or an associative array found in other programming languages.
Iterating through a hash is an essential operation when you want to
access all the elements in the hash. In this blog post, we will discuss
different ways to iterate over a hash in Ruby.

Using the `each` method

The most common way to iterate over a hash is to use the
each method. The each method takes a
block, and for each key-value pair, it passes the key and value to the
block as arguments.

Let’s say we have the following hash, where key is the student name and
value is their age:

students = {
  "John" => 25,
  "Jane" => 22,
  "Mark" => 28,
  "Lucy" => 23
}

We can iterate over the hash and print each key-value pair using the
each method as follows:

students.each do |name, age|
  puts "#{name} is #{age} years old"
end

Using the `each_key` and `each_value` methods

Sometimes, you only need to iterate over the keys or the values of the
hash. In such cases, you can use the each_key and
each_value methods.

The each_key method iterates over the keys of the hash,
and for each key, it passes the key to the block as an argument. Here’s
an example of how to use the each_key method with our
students hash:

students.each_key do |name|
  puts "Student name: #{name}"
end

The each_value method iterates over the values of the
hash, and for each value, it passes the value to the block as an
argument. Here’s an example of how to use the
each_value method with our students hash:

students.each_value do |age|
  puts "Student age: #{age}"
end

Using the `map` method

If you want to create a new array while iterating over the hash, you can
use the map method. The map method works
like the each method, but instead of returning the
original hash, it returns a new array containing the results of the
block for each key-value pair. Here’s an example of how to use the
map method with our students hash:

students_info = students.map do |name, age|
  "#{name} is #{age} years old"
end

puts students_info

In this example, the students_info variable will be an
array containing strings with the student names and ages.

Conclusion

In this blog post, we discussed different ways to iterate over a hash in
Ruby, including using the each,
each_key, each_value, and
map methods. By understanding and using these methods,
you’ll be able to work with hashes effectively in your Ruby programs.