What is hash.clear in Ruby?
Overview
We can use the clear method to clear all the entries of a hash.
Syntax
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 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
In the above code snippet:
- Lines 2 to 4: We create hashes
h1,h2, andh3with 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
clearmethod. - 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.