Home »
Ruby programming
Hash.reject! Method with Example in Ruby
Ruby Hash.reject! Method: Here, we are going to learn about the Hash.reject! Method with examples in Ruby programming language.
Submitted by Hrithik Chandra Prasad, on March 13, 2020
Hash.reject! Method
In this article, we will study about Hash.reject! 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. The changes created by this method are permanent or non-temporary because this method is an example of destructive methods. This method works in a way that it will delete all the keys for which the block has been evaluated to be false. If you are not providing any block then an enumerator will be returned.
Syntax:
Hash_object.reject!{|key,value| block}
Argument(s) required:
This method does not require any argument. However, a block can be passed for the desired result.
Example 1:
=begin
Ruby program to demonstrate reject! method
=end
hsh = Hash.new()
hsh["color"] = "Black"
hsh["age"] = 20
hsh["school"] = "Angels' Academy Haridwar"
hsh["college"] = "Graphic Era University"
puts "Hash reject! implementation"
puts "#{hsh.reject!{|key,value| key>="school"}}"
puts "Hash contents are : #{hsh}"
Output
Hash reject! implementation
{"color"=>"Black", "age"=>20, "college"=>"Graphic Era University"}
Hash contents are : {"color"=>"Black", "age"=>20, "college"=>"Graphic Era University"}
Explanation:
In the above code, you can observe that we are removing keys from the hash object based on some condition. The method is returning a hash which is containing all those keys which stood false when the condition was tested on them. The method is creating permanent change on the hash object.
Example 2:
=begin
Ruby program to demonstrate reject! method
=end
hsh = Hash.new()
hsh["color"] = "Black"
hsh["age"] = 20
hsh["school"] = "Angels' Academy Haridwar"
hsh["college"] = "Graphic Era University"
puts "Hash reject! implementation"
puts "#{hsh.reject!}"
puts "Hash contents are : #{hsh}"
Output
Hash reject! implementation
#<Enumerator:0x000055b6246cff40>
Hash contents are : {"color"=>"Black", "age"=>20, "school"=>"Angels' Academy Haridwar", "college"=>"Graphic Era University"}
Explanation:
In the above code, you can observe that when we are invoking the method without any block, an enumerator has been returned without creating any changes in the actual hash.