Open In App

Ruby | Hash each() function

Improve
Improve
Like Article
Like
Save
Share
Report

Hash#each() is a Hash class method which finds the nested value which calls block once for each key in hash by passing the key-value pair as parameters.

Syntax: Hash.each()

Parameter: Hash values

Return: calls block once for each key in hash otherwise Enumerator if no argument is passed.

Example #1 :




# Ruby code for Hash.each() 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 form : #{a.each()}\n\n"
  
puts "Hash b each form : #{b.each {|key| puts "#{key}"}}\n\n"
  
puts "Hash c each form : #{c.each {|value| puts "#{value}"}}\n\n"


Output :

Hash a each form : #

[:a, 100]
[:c, 300]
[:b, 200]
Hash b each form : {:a=>100, :c=>300, :b=>200}

[:a, 100]
Hash c each form : {:a=>100}

Example #2 :




# Ruby code for Hash.each() 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 form : #{a.each()}\n\n"
  
puts "Hash b each form : #{b.each {|key| puts "#{key}"}}\n\n"
  
puts "Hash c each form : #{c.each {|value| puts "#{value}"}}\n\n"


Output :

Hash a each form : #

["a", 100]
Hash b each form : {"a"=>100}

["a", 100]
["c", 300]
["b", 200]
Hash c each form : {"a"=>100, "c"=>300, "b"=>200}



Last Updated : 07 Jan, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads