How to remove all hash entries in Ruby

Overview

The clear method is used to clear all entries of a hash in Ruby. It removes all hash entries and returns the hash.

Syntax

hash.clear

Return value

This method returns the hash itself.

Example

Let’s look at the code below:

# create some hashes
h1 = {one: 1, two: 2, three: 3}
h2 = {name: "okwudili", stack: "ruby"}
h3 = {"foo": 0, "bar": 1}
# print all hashes
puts h1
puts h2
puts h3
# clear all hashes
h1.clear
h2.clear
h3.clear
# Reprint hashes
puts h1
puts h2
puts h3

Explanation

  • Lines 2 to 4: We create hashes h1, h2, and h3 with some entries.
  • Lines 7 to 9: We print all hashes to the console.
  • Lines 12 to 14: We clear the entries of the hashes by using the clear method.
  • Lines 17 to 19: We reprint the hashes (with cleared elements) to the console.

When we run the code, the hash entries are cleared using the clear method.