Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

hash
ruby
communitycreator

What is hash.clear in Ruby?

okwudili onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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 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
Clearing hash entries in Ruby

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.

RELATED TAGS

hash
ruby
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring