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 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
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
clearmethod to clear or empty theNumbersToTenset. - 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.