What is hash.clear in Ruby?

Overview

We can use the **`clear` method** to clear all the entries of a hash.

Syntax

```ruby hash.clear ```

Parameters

**`hash`**: This is the hash object we want to clear.

Return value

This method returns `hash`, but with its entries cleared.

Example

# 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

In the above code snippet: * **Lines 2 to 4**: We create hashes `h1`, `h2`, and `h3` with some entries. * **Lines 7 to 9**: We print the 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 to the console.

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

Free Resources