Ruby | Hash each_pair() function
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 valuea = {a:100, b:200} # declaring Hash valueb = {a:100, c:300, b:200} # declaring Hash valuec = {a:100} # each Valueputs "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 valuea = { "a" => 100, "b" => 200 } # declaring Hash valueb = {"a" => 100} # declaring Hash valuec = {"a" => 100, "c" => 300, "b" => 200} # each Valueputs "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}


