In Ruby, the minus operator -
is used to obtain the difference between the two sets. Remember that a set is a collection of unordered values with no duplicates. The difference between the two sets is all the elements of the first set that are not in the other set.
A = {1, 2, 3}
B = {2, 4, 6}
A - B = {1, 2, 3} - {2, 4, 6} = {1, 3}
set1 - set2
set 1
and set2
: We'll find the difference between these two sets.
We obtain a set with a return value, which contains all the elements of set1
other than the ones in set2
.
# 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 intersectiondifference1 = NumbersToTen - EvenNumbersdifference2 = Workers - Names# print out intersectsputs "#{difference1.to_a}"puts "#{difference2.to_a}"
require
to obtain the set
class.Note: if you change the position of the parameters then you will get the empty set, for example,EvenNumbers - NumbersToTen
andNames - Workers
will give us the empty set.