In Ruby, we use the ampersand operator &
to find the intersection for two sets. The intersection of two sets means a new set containing elements common in the two sets.
set1 & set2
set1
: This is the first set for which we need to find the intersection with another set set2
.
set2
: This is the second of the two sets for the intersection.
This is a new return set containing elements common to both set1
and 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 intersectionIntersect1 = EvenNumbers & NumbersToTenIntersect2 = Names & Workers# print out intersectsputs "#{Intersect1.to_a}"puts "#{Intersect2.to_a}"
require
to get the set instance. &
operator to get the intersects of the sets.