Let us say, we have a Hash that contains,
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.
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
x = { 5 => "Is a Number", "John" => "Is a Name", "Ruby" => "Is a Language" } x.delete(5) puts x
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.
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.
And we get the below output,
The clear() Method can be used to remove all the elements from the Hash.
x = { 5 => "Is a Number", "John" => "Is a Name", "Ruby" => "Is a Language" } x.clear() puts x
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.
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.