How to Delete an Entry of a Hash by Specifying its Key in Ruby?
Last Updated :
23 Jul, 2025
Hashes is one of the most important data structures in Ruby. In this article, we will learn how to delete an entry of a hash by specifying its key in Ruby. We will discuss various approaches on how to delete an entry of a hash by specifying its key in Ruby.
Prerequisites
Before learning how to add key-value pairs to hashes in Ruby, we should have:
- Install Ruby.
- Basics of Ruby Programming.
What is Hash?
A hash is a collection of unique keys and their associated values pair.
- In Ruby, hashes are created using curly braces {} with key-value pairs separated by commas.
- They are similar to arrays, but they use keys as numerical indices to access elements.
Deleting an Entry from a Hash by Key
1. Using the delete Method
In this method we use delete method to delete a key-value pair from a hash. Here we pass the key we want to remove as an argument.
Syntax:
hash.delete(key)
- Example: In this example we use delete keyword to delete an entry New Delhi of the hash by specifying its key city in Ruby
Ruby
person = { "name" => "Geeks", "age" => 20, "city" => "New Delhi" }
person.delete("city")
puts person
Output{"name"=>"Geeks", "age"=>20}
2. Using the delete_if Method
In this we use delete_if method to remove key-value pairs for which the block returns true.
Syntax:
hash.delete_if { |key, value| condition }
- Example: In this example we use delete_if keyword to delete an entry New Delhi of the hash by specifying its key city in Ruby
Ruby
person = { "name" => "Geeks", "age" => 20, "city" => "New Delhi" }
person.delete_if { |key, _value| key == "age" }
puts person
Output{"name"=>"Geeks", "city"=>"New Delhi"}
3. Using the reject! Method
The reject! method is similar to delete_if, but it returns nil if no changes are made to the hash.
Syntax:
hash.reject! { |key, value| condition }
- Example: In this example we use reject! keyword to delete an entry New Delhi of the hash by specifying its key city in Ruby
Ruby
person = { "name" => "Geeks", "age" => 20, "city" => "New Delhi" }
person.reject! { |key, _value| key == "city" }
puts person
Output{"name"=>"Geeks", "age"=>20}
Conditional Deletion
We can also delete key-value pairs from a hash based on specific conditions. For example, deleting entries where the value matches a condition.
Example: In this we delete key-value pairs from a hash based on specific conditions.
Ruby
person = { "name" => "Geeks", "age" => 20, "city" => "New Delhi" }
person.delete_if { |key, value| value == 20 }
puts person
Output{"name"=>"Geeks", "city"=>"New Delhi"}
Conclusion
In Ruby, there are various ways to delete entries from a hash by specifying its key. The delete method is the most straightforward, but methods like delete_if and reject! provide additional flexibility when we need to delete based on conditions. Choosing the right method depends on your specific use case.