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.
set.empty?()
set
: This is the set that we want to check for emptiness.
The value returned is a boolean. If the set is empty, then true
is returned. Otherwise, false
is returned.
# require the set classrequire "set"# create some setsEvenNumbers = 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 setNumbersToTen.clear# check if sets are emptyputs EvenNumbers.empty?() # falseputs NumbersToTen.empty?() # trueputs Workers.empty?() # falseputs EmptySet.empty?() # true
clear
method to clear or empty the NumbersToTen
set.empty?()
method, we check each set to determine whether it is empty or not. We print the corresponding results to the console.