Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
hash
communitycreator

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

okwudili onyejiaku

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
Deleting some entries of a Hash using the delete(key) method

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.

RELATED TAGS

ruby
hash
communitycreator
RELATED COURSES

View all Courses

Keep Exploring