Deleting elements from a hash
In this section, we'll examine how to delete items from a Ruby hash. Let's start by creating a new hash called people
. It will contain the names and ages of people:
people = { jordan: 32, tiffany: 27, kristine: 10, heather: 29 }
I can confirm that this is working by attempting to select a value using the following code:
people[:tiffany]
The preceding code will return the value of 27
.
Deleting from a hash is similar to how you would do it from an array, except, instead of an index, we'll pass the key as a symbol:
people.delete(:kristine)
This method not only deletes that record from the hash but also returns the value, which in this case, is the age of kristine
.
Now, if you go to the hash, you can see that it has only three key/value pairs instead of the original four, because one was deleted:

So, that's how you can delete values from a hash.