0
0
RubyHow-ToBeginner · 3 min read

How to Delete a Key from a Hash in Ruby: Simple Guide

In Ruby, you can delete a key from a hash using the delete method, like hash.delete(key). This removes the key and its value from the hash and returns the deleted value or nil if the key is not found.
📐

Syntax

The delete method removes a key and its associated value from a hash.

  • hash: The hash you want to modify.
  • key: The key you want to remove.
  • The method returns the value of the deleted key or nil if the key does not exist.
ruby
hash.delete(key)
💻

Example

This example shows how to delete a key from a hash and what happens to the hash after deletion.

ruby
person = { name: "Alice", age: 30, city: "New York" }
removed_value = person.delete(:age)
puts "Removed value: #{removed_value}"
puts "Updated hash: #{person}"
Output
Removed value: 30 Updated hash: {:name=>"Alice", :city=>"New York"}
⚠️

Common Pitfalls

One common mistake is trying to delete a key that does not exist, which returns nil and does not change the hash. Another is confusing delete with delete_if, which deletes keys based on a condition.

ruby
# Wrong: expecting error if key missing
h = {a: 1, b: 2}
puts h.delete(:c) # returns nil, no error

# Right: check if key exists before deleting
if h.key?(:c)
  h.delete(:c)
else
  puts "Key :c not found"
end
Output
nil Key :c not found
📊

Quick Reference

MethodDescriptionReturn Value
delete(key)Removes key and value from hashValue of deleted key or nil if not found
delete_if { |k, v| condition }Deletes keys matching conditionModified hash
key?(key)Checks if key exists in hashtrue or false

Key Takeaways

Use hash.delete(key) to remove a key and its value from a Ruby hash.
The delete method returns the deleted value or nil if the key is missing.
Check if a key exists with hash.key?(key) before deleting to avoid unexpected nil returns.
Do not confuse delete with delete_if, which deletes keys based on a condition.
Deleting a non-existent key does not raise an error; it simply returns nil.