How to iterate over a Hash in Ruby?
Last Updated :
27 Mar, 2024
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 }
Outputapple
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 }
Outputapple
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 }
Share your thoughts in the comments
Please Login to comment...