How to check if a Hash is empty in Ruby

Overview

When we say a Hash is empty, what we mean is that the Hash has no entries.

We can use the empty? method to check if a Hash has no entries. This method returns a Boolean, which indicates whether the Hash is empty or not.

Syntax

The syntax is given below:

hash.empty?

Parameters

hash: This is the hash we want to check to see if it is empty or not.

Return value

The value returned is a Boolean value. If the Hash is empty, then True is returned. If a Hash is not empty, then False is returned.

Code example

# create hashes
h1 = {one: 1, two: 2, three: 3}
h2 = {}
h3 = {name: "okwudili", stack: "ruby"}
h4 = {"foo": 0, "bar": 1}
h5 = Hash[]
# check if empty and
# print results
puts h1.empty? # false
puts h2.empty? # true
puts h3.empty? # false
puts h4.empty? # false
puts h5.empty? # true

Code explanation

  • Lines 2–6: We create Hashes.
  • Lines 10–14: We check the Hashes to see if they are empty. Then, we print the results to the console.

Free Resources