Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Ruby | Hash each_pair() function

  • Last Updated : 07 Jan, 2020

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}




My Personal Notes arrow_drop_up
Recommended Articles
Page :