What is set.disjoint?() in Ruby?
Overview
In Ruby, the disjoint?()method is used on sets. A set is a collection of unordered unique elements. When this method is called, it returns a Boolean value. If two sets have no element in common then we say they are disjoint. A disjoint is the opposite of an intersection.
Syntax
set1.disjoint?(set2)
Syntax for the disjoint?() method of a set in Ruby
Parameters
set1 and set2: We want to check if set1 and set2 are disjoint.
Return value
The value returned is a Boolean. true is returned if the two sets have no element in common, that is they are disjoint. Otherwise, false is returned.
Example
# require set classrequire "set"# create some setsset1 = Set.new([1, 2, 3])set2 = Set.new([4..5])set3 = Set.new([3, 4])set4 = Set.new([4, 5])# check if disjoint setsputs set1.disjoint? set2 # trueputs set1.disjoint? set3 # falseputs set1.disjoint? set4 # true
Explanation
- Line 2: We require the
setclass. - Lines 5–8: We create and initialize four sets for comparison purposes.
- Lines 11–13: We check if the sets are disjoint using the
disjoint?method and print the results to the console.