Home »
Ruby programming
Hash.delete() Method with Example in Ruby
Ruby Hash.delete() Method: Here, we are going to learn about the Hash.delete() Method with examples in Ruby programming language.
Submitted by Hrithik Chandra Prasad, on February 20, 2020
Hash.delete() Method
In this article, we will study about Hash.delete() 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 deletes the key-value pair of the key which is passed with the method at the time of invocation. If the key is not found, it returns 'nil'. To avoid the 'nil' value, you can pass a block along with the method then the result of that value will be returned in case the key is not found.
Syntax:
Hash_object.delete(object)
or
Hash_object.delete(object){block}
Argument(s) required:
You can pass at most one object along with this method. An optional block can be given in order to avoid 'nil' value return.
Example 1:
=begin
Ruby program to demonstrate delete method
=end
hsh = Hash.new()
hsh["color"] = "Black"
hsh["age"] = 20
hsh["school"] = "Angels' Academy Haridwar"
hsh["college"] = "Graphic Era University"
puts "Hash delete implementation"
puts "Enter the key you want to delete:"
ky = gets.chomp
if(hsh.delete(ky))
puts "Key deleted successfully"
else
puts "Key not found"
end
puts "Hash contents are : #{hsh}"
Output
Hash delete implementation
Enter the key you want to delete:
school
Key deleted successfully
Hash contents are : {"color"=>"Black", "age"=>20, "college"=>"Graphic Era University"}
Explanation:
In the above code, you can observe that the method is creating permanent changes on the hash object and the key along with its value has been deleted from the hash object.
Example 2:
=begin
Ruby program to demonstrate delete method
=end
hsh = Hash.new()
hsh["color"] = "Black"
hsh["age"] = 20
hsh["school"] = "Angels' Academy Haridwar"
hsh["college"] = "Graphic Era University"
puts "Hash delete implementation"
puts "Enter the key you want to delete:"
ky = gets.chomp
puts "#{hsh.delete(ky){|ky|"#{ky} not found"}}"
puts "Hash contents are : #{hsh}"
Output
Hash delete implementation
Enter the key you want to delete:
car
car not found
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 the key is not found in the hash object then the block has been executed and the block processed value has been returned. This is possible with the help of the block otherwise 'nil' value must have been returned from the delete() method.