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 hashesh1 = {one: 1, two: 2, three: 3}h2 = {name: "okwudili", stack: "ruby"}h3 = {"foo": 0, "bar": 1}# print all hashesputs h1puts h2puts h3# clear all hashesh1.clearh2.clearh3.clear# Reprint hashesputs h1puts h2puts h3
Explanation
- Lines 2 to 4: We create hashes
h1,h2, andh3with 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
clearmethod. - 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.