What is set.empty?() in Ruby?

Overview

In Ruby, we can check whether a set is empty or not by using the empty?() method. In Ruby, a set is a collection of unordered, unique and non-duplicated elements. Sometimes a set can become empty, and here is when the empty?() method comes in handy.

Syntax

set.empty?()

Parameters

set: This is the set that we want to check for emptiness.

Return value

The value returned is a boolean. If the set is empty, then true is returned. Otherwise, false is returned.

Example

# require the set class
require "set"
# create some sets
EvenNumbers = Set.new([2, 4, 6, 8, 10])
NumbersToTen = Set.new([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
Workers = Set.new(["Amaka", "Chioma", "Titi"])
EmptySet = Set.new([])
# clear a particular set
NumbersToTen.clear
# check if sets are empty
puts EvenNumbers.empty?() # false
puts NumbersToTen.empty?() # true
puts Workers.empty?() # false
puts EmptySet.empty?() # true

Explanation

  • Line 2: We require the set class.
  • Lines 5–8: We created some set instances, one of which is an empty set.
  • Line 11: We use the clear method to clear or empty the NumbersToTen set.
  • Lines 14–17: Using the empty?() method, we check each set to determine whether it is empty or not. We print the corresponding results to the console.

New on Educative
Learn any Language for FREE all September 🎉
For the entire month of September, get unlimited access to our entire catalog of beginner coding resources.
🎁 G i v e a w a y
30 Days of Code
Complete Educative’s daily coding challenge every day in September, and win exciting Prizes.

Free Resources