Home »
Ruby programming
Hash.length Method with Example in Ruby
Ruby Hash.length Method: Here, we are going to learn about the Hash.length Method with examples in Ruby programming language.
Submitted by Hrithik Chandra Prasad, on March 14, 2020
Hash.length Method
In this article, we will study about Hash.length 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 it iterates over the whole hash object and gives the number of key-value pairs that are present in the hash object. This method will return 0 if it finds the absence of any of the keys after successfully traversing the hash object.
Syntax:
Hash_object.length
Argument(s) required:
This method does not require any argument. This method simply returns the length of the hash instance.
Example 1:
=begin
Ruby program to demonstrate length method
=end
hash1={"color"=>"Black","object"=>"car","love"=>"friends","fruit"=>"Kiwi","vege"=>"potato"}
puts "Hash length implementation"
cnt = hash1.length
puts "Length of hash object is :#{cnt}"
puts "Self hash object : #{hash1}"
Output
Hash length implementation
Length of hash object is :5
Self hash object : {"color"=>"Black", "object"=>"car", "love"=>"friends", "fruit"=>"Kiwi", "vege"=>"potato"}
Explanation:
In the above code, you can observe that we are finding the length of the hash object with the help of the Hash.length() method. You can see that the numbers of keys present in the hash object are 5 and the method is returning five after traversing the whole hash object.
Example 2:
=begin
Ruby program to demonstrate length method
=end
hash1= Hash.new { |hash, key| hash[key] = "Not present" }
puts "Hash length implementation"
cnt = hash1.length
puts "Number of keys present in the hash :#{cnt}"
puts "Self hash object : #{hash1}"
Output
Hash length implementation
Number of keys present in the hash :0
Self hash object : {}
Explanation:
In the above code, you can observe that we are finding the length of the hash object with the help of the Hash.length() method. You can see that the number of keys present in the hash object is 0 and the method is returning zero because the hash on which the method has been invoked is an empty hash.