Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




RUBY - REMOVE FROM HASH


How to remove an element from the Hash?


Let us say, we have a Hash that contains,

5, Is a Number

John, Is a Name

Ruby, Is a Language

As Key and Value pair.


Now, if you want to remove the entries from a Hash, delete(), clear() Method can be used.


Let us look at the delete() Method first.


How to remove an element using the delete() Method?


The delete() Method can be used to remove an item from the Hash.


Let us say, we want to remove the entry where the Key is 5 and Value is Is a Number.


5, Is a Number


Example :



x = {
	5 => "Is a Number", 
	"John" => "Is a Name", 
	"Ruby" => "Is a Language"
}
x.delete(5)
puts x


Output :



  {"John"=>"Is a Name", "Ruby"=>"Is a Language"}

So, in the above code we have created a Hash using braces {} and Key and Value pairs.


x = {
	5 => "Is a Number",
	"John" => "Is a Name",
	"Ruby" => "Is a Language"
}

And initialised to the variable x.

java_Collections

Now, we are supposed to delete the value of the Key, 5.


So, we have used delete() method to delete it.


x.delete(5)

And the entry for the Key 5 is deleted for the Hash.

java_Collections

And we get the below output,

Output :



  {"John"=>"Is a Name", "Ruby"=>"Is a Language"}

How to remove all the elements from the Hash using clear() Method?


The clear() Method can be used to remove all the elements from the Hash.


Example :



x = {
	5 => "Is a Number", 
	"John" => "Is a Name", 
	"Ruby" => "Is a Language"
}
x.clear()
puts x


Output :



  {}

So, in the above code we have created a Hash using braces {} and Key and Value pairs.


x = {
	5 => "Is a Number",
	"John" => "Is a Name",
	"Ruby" => "Is a Language"
}

And initialised to the variable x.

java_Collections

And we have used the clear() method to remove all the elements from the Hash.


x.clear()

And the print statement, prints an empty Hash.

Output :



  {}