How to delete an entry of a hash by specifying its key in Ruby

Overview

We can use the delete(key) method to delete an entry of a hash. It returns the associated value of the entry deleted.

Syntax

hash.delete(key)

Parameters

hash: The hash we want to delete an entry from.

Return value

This method returns the value of the entry deleted.

Example

Let’s look at the code below:

# create hashes
h1 = {one: 1, two: 2, three: 3}
h2 = {name: "okwudili", stack: "ruby"}
h3 = {"foo": 0, "bar": 1}
# delete some keys
# and print return values
puts h1.delete(:three)
puts h2.delete(:stack)
puts h3.delete(:bar)
# now print hashes
puts h1
puts h2
puts h3

Explanation

  • Lines 2 to 4: We create three hashes h1, h2, and h3.
  • Lines 8 to 10: We invoke the delete(key) method on the hashes and print their returned values.
  • Lines 13 to 15: We print the hashes after some entries are deleted.

Free Resources