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 hashesh1 = {one: 1, two: 2, three: 3}h2 = {}h3 = {name: "okwudili", stack: "ruby"}h4 = {"foo": 0, "bar": 1}h5 = Hash[]# check if empty and# print resultsputs h1.empty? # falseputs h2.empty? # trueputs h3.empty? # falseputs h4.empty? # falseputs 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.