Open In App

Ruby | Hash each_pair() function

Last Updated : 07 Jan, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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 :




# Ruby code for Hash.each_pair() method
   
# declaring Hash value
a = {a:100, b:200}
   
# declaring Hash value
b = {a:100, c:300, b:200}
   
# declaring Hash value
c = {a:100}
   
# each Value
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 :




# Ruby code for Hash.each_pair() method
   
# declaring Hash value
a = { "a" => 100, "b" => 200 }
   
# declaring Hash value
b = {"a" => 100}
   
# declaring Hash value
c = {"a" => 100, "c" => 300, "b" => 200}
   
# each Value
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}



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads