Hash#each_pair() is a Hash class method which finds the nested value which calls block once for each pair in hash by passing the key_value pair as parameters.
Syntax: Hash.each_pair()
Parameter: Hash values
Return: calls block once for key_value pair in hash with key_value pair as parameter otherwise Enumerator if no argument is passed.
Example #1 :
a = {a: 100 , b: 200 }
b = {a: 100 , c: 300 , b: 200 }
c = {a: 100 }
puts "Hash a each_pair form : #{a.each_pair()}\n\n"
puts "Hash b each_pair form : #{b.each_pair {|key| puts " #{key} "}}\n\n"
puts "Hash c each_pair form : #{c.each_pair {|value| puts " #{value} "}}\n\n"
|
Output :
Hash a each_pair form : #
[:a, 100]
[:c, 300]
[:b, 200]
Hash b each_pair form : {:a=>100, :c=>300, :b=>200}
[:a, 100]
Hash c each_pair form : {:a=>100}
Example #2 :
a = { "a" => 100 , "b" => 200 }
b = { "a" => 100 }
c = { "a" => 100 , "c" => 300 , "b" => 200 }
puts "Hash a each_pair form : #{a.each_pair()}\n\n"
puts "Hash b each_pair form : #{b.each_pair {|key| puts " #{key} "}}\n\n"
puts "Hash c each_pair form : #{c.each_pair {|value| puts " #{value} "}}\n\n"
|
Output :
Hash a each_pair form : #
["a", 100]
Hash b each_pair form : {"a"=>100}
["a", 100]
["c", 300]
["b", 200]
Hash c each_pair form : {"a"=>100, "c"=>300, "b"=>200}
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
07 Jan, 2020
Like Article
Save Article