Home »
Ruby Tutorial
Ruby Set disjoint? Method
By IncludeHelp Last updated : December 01, 2024
Description and Usage
Disjoint?(Set) method is predefined in Ruby's library. With the help of this method, we can check whether the two sets are having any common elements. If the sets which we are comparing are having any of the common elements then the method will return false and it will be true in the case only when there are no common elements in both the sets. This method may be proved very advantageous some of the time while programming with Ruby. Let us see its syntax and example for having a better understanding of how this method is implemented in the Ruby code.
Syntax
Set.disjoint?(Set)
Example 1
=begin
Ruby program to demonstrate the
implementation of disjoint?() method.
=end
require 'set'
Vegetable=Set.new(["potato", "brocolli","broccoflower","lentils","peas","fennel","chilli","cabbage"])
Fruits = Set.new(["Apple","Mango","Banana","Orange","Grapes"])
p = Vegetable.disjoint?(Fruits)
if p == true
puts "There is no common element exists between both the sets."
else
puts "The sets are having common elements."
end
Output
There is no common element exists between both the sets.
Explanation
In the above code, we have declared two instance of Set class known as Vegetable and Fruits. We want to check whether there exist some common elements between both the sets or not. We are proceeding with the help of disjoint? method. We know that it returns a Boolean value. So, we are storing its value inside a variable. We are then checking the value of that variable, if it is true then it simply means that there are no common elements between both the sets. This method will give you result as false even if there is only one element which is common between both the instances of Set class.
Example 2
=begin
Ruby program to show the implementation of disjoint?() .
=end
require 'set'
p = Set[2,3,5].disjoint?Set[2,56,4,3,22,66,34]
if p == true
puts "There is no common element exists between both the sets."
else
puts "The sets are having common elements."
end
Output
The sets are having common elements.
Explanation
In the above code, we are creating sets at the time of invoking the disjoint? function. The function disjoint?() is checking whether both the sets are having some common elements or not. If the sets are having even a single common element then it will return true. We are storing its returned value inside a variable ‘p’. We are checking the value of p, if it is having true then it means that there are some common elements inside both the sets. We are informing the user about this with the help of puts statements.