The difference()
method of a set in Ruby is used to find the difference between two sets. This method returns a new set by duplicating the set that invokes it and by removing each of its elements that are also present in the other set. For example, if setA
has the elements [1,2,3]
and setB
has the elements [2,3]
and the `difference()` method is invoked with setA
and setB
as parameters, the returned result will be [1]
.
set1.difference(set2)
set1
: This is the set that is duplicated and has its elements removed if they are also found in the other set, set2
.set2
: This is the set we want to compare with the set set1
.The difference()
method returns a new set that is a duplicate of set1
.
# require setrequire "set"# create some setsEvenNumbers = Set.new([2, 4, 6, 8, 10])NumbersToTen = Set.new([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])Names = Set.new(["Amaka", "Titi"])Workers = Set.new(["Amaka", "Chioma", "Titi"])# get the differencedifference1 = NumbersToTen.difference(EvenNumbers)difference2 = Workers.difference(Names)# print out intersectsputs "#{difference1.to_a}"puts "#{difference2.to_a}"
set
class.