Home »
Ruby Tutorial
Ruby Hash.compact! Method
By IncludeHelp Last updated : December 01, 2024
In this article, we will study about Hash.compact! 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.
Description and Usage
This method is a public instance method that is defined in Ruby's library especially for Hash class. This method is one of the examples of destructive methods where the changes brought by the method are permanent or not temporary. This type of method affects the self Hash instance. This method works in a way that removes all the keys from the hash which are containing nil values and returns a new Hash object which does not contain any nil value.
Syntax
Hash_object.compact!
Parameters
This method does not take any argument.
Example 1
=begin
Ruby program to demonstrate compact! method
=end
hash1={"color"=>"Black","object"=>nil,"love"=>"mom","fruit"=>"Kiwi","vege"=>"potato"}
puts "Hash compact! implementation"
puts "Elements after compact! operation: #{hash1.compact!}"
puts "Array elements are:"
puts "#{hash1}"
Output
Hash compact! implementation
Elements after compact! operation: {"color"=>"Black", "love"=>"mom", "fruit"=>"Kiwi", "vege"=>"potato"}
Array elements are:
{"color"=>"Black", "love"=>"mom", "fruit"=>"Kiwi", "vege"=>"potato"}
Explanation
In the above code, you can observe that we are removing nil value keys from the hash object with the help of the Hash.compact method. This method is bringing changes in the actual hash instance because this method is an example of the destructive method and you can observe this by yourself when the program is printing the original hash on which the method has been invoked.
Example 2
=begin
Ruby program to demonstrate compact! method
=end
hash1={"color"=>[nil,nil,"black"],"object"=>nil,"love"=>"mom","fruit"=>"Kiwi","vege"=>"potato"}
puts "Hash compact! implementation"
puts "Elements after compact! operation: #{hash1.compact!}"
puts "Array elements are:"
puts "#{hash1}"
Output
Hash compact! implementation
Elements after compact! operation: {"color"=>[nil, nil, "black"], "love"=>"mom", "fruit"=>"Kiwi", "vege"=>"potato"}
Array elements are:
{"color"=>[nil, nil, "black"], "love"=>"mom", "fruit"=>"Kiwi", "vege"=>"potato"}
Explanation
In the above code, you can observe that Hash.compact! method does not work upon the hashes which have keys along with more than one value. The method is returning the original hash without removing the nil value keys.