Home »
Ruby programming
Hash.each Method with Example in Ruby
Ruby Hash.each Method: Here, we are going to learn about the Hash.each Method with examples in Ruby programming language.
Submitted by Hrithik Chandra Prasad, on February 20, 2020
Hash.each Method
In this article, we will study about Hash.each Method. The working of this method can be predicted with the help of its name but it is not as simple as it seems. Well, we will understand this method with the help of its syntax and program code in the rest of the content.
Method description:
This method is a public instance method that is defined in the ruby library especially for Hash class. This method works in a way that invokes the block at least once for every individual key present in the hash object. The key-value pairs present in the hash object are passed as parameters. If you are not providing any block then you should expect an enumerator as the returned value from each method.
Syntax:
Hash_object.each{|key,value| block}
Argument(s) required:
This method does not accept any arguments. However, you can pass a block along with this method.
Example 1:
=begin
Ruby program to demonstrate each method
=end
hsh={"name"=>"Zorawar","class"=>"ukg","school"=>"AASSC","place"=>"Haridwar"}
puts "Hash each implementation"
str = hsh.each{|key,value| puts "#{key} is #{value}"}
puts str
Output
Hash each implementation
name is Zorawar
class is ukg
school is AASSC
place is Haridwar
{"name"=>"Zorawar", "class"=>"ukg", "school"=>"AASSC", "place"=>"Haridwar"}
Explanation:
In the above code, you may observe that we are printing every key-value pair from the hash object with the help of the Hash.each method. The method is invoking a block, which is taking the key value as the argument from the hash object. This method is traversing through the hash object, processing them and giving us the desired output or you can say that letting us know about the value stored in a particular key.
Example 2:
=begin
Ruby program to demonstrate each method
=end
hsh={"name"=>"Zorawar","class"=>"ukg","school"=>"AASSC","place"=>"Haridwar"}
puts "Hash each implementation"
str = hsh.each
puts str
Output
Hash each implementation
#<Enumerator:0x0000558aa3b8d8b8>
Explanation:
In the above code, you can observe that when we are invoking the method without the block then we are getting an enumerator returned from the method.