Home » Ruby programming

Hash.each_pair Method with Example in Ruby

Ruby Hash.each_pair Method: Here, we are going to learn about the Hash.each_pair Method with examples in Ruby programming language.
Submitted by Hrithik Chandra Prasad, on February 20, 2020

Hash.each_pair Method

In this article, we will study about Hash.each_pair 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 the 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 the each_pair method.

Syntax:

    Hash_object.each_pair{|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_pair method
=end

hsh={"name"=>"Zorawar","class"=>"ukg","school"=>"AASSC","place"=>"Haridwar"}

puts "Hash each_pair implementation"

str = hsh.each_pair{|key,value| puts "#{key} is #{value}"}
puts str

Output

Hash each_pair 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_pair 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_pair method
=end

hsh={"name"=>"Zorawar","class"=>"ukg","school"=>"AASSC","place"=>"Haridwar"}

puts "Hash each_pair implementation"

str = hsh.each_pair
puts str

Output

Hash each_pair implementation
#<Enumerator:0x0000560701eb6820>

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.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.