Open In App

How to iterate over a Hash in Ruby?

Last Updated : 27 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss how to iterate over a hash in Ruby. By Iterating over a hash we can access key-value pairs and perform operations on them. Let us study different methods to iterate over a hash in ruby

Iterating over a hash using each method

Each method allows us to iterate over each key-value pair in the hash and executes the provided block with two arguments: the key and the value.

Syntax:

hash.each { |key, value| block }

Example: In this example we’re printing each key-value pair in hash fruits

Ruby
#Ruby program to Iterate over a hash using each method:


fruits = { "apple" => 5, "banana" => 3, "orange" => 6 }

# Iterate over each key and print them
fruits.each_key { |fruit| puts fruit }

Output
apple
banana
orange

Iterating over a hash using each_key method:

The each method allows us to iterates over each key in the hash and executes the provided block with one argument: the key.

Syntax:

hash.each_key { |key| block }

Example: In this example we’re printing each key of hash fruits

Ruby
#Ruby program to Iterate over a hash using each_key method:

fruits = { "apple" => 5, "banana" => 3, "orange" => 6 }

# Iterate over each key and print them
fruits.each_key { |fruit| puts fruit }

Output
apple
banana
orange

Iterating over a hash using each_value method:

The each method allows us to iterates over each value in the hash and executes the provided block with one argument: the value

Syntax:

hash.each_value { |value| block }

Example: In this example we’re printing each value of hash fruits

Ruby
#Ruby program to Iterate over a hash using each_value method:


fruits = { "apple" => 5, "banana" => 3, "orange" => 6 }

# Iterate over each value and print them
fruits.each_value { |quantity| puts quantity }

Output
5
3
6

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads