How to get the intersection of two sets in Ruby

Overview

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.

Syntax

set1 & set2
Syntax to get intersection of two sets in Ruby

Parameters

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.

Return value

This is a new return set containing elements common to both set1 and set2.

Example

# require set
require "set"
# create some sets
EvenNumbers = 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 intersection
Intersect1 = EvenNumbers & NumbersToTen
Intersect2 = Names & Workers
# print out intersects
puts "#{Intersect1.to_a}"
puts "#{Intersect2.to_a}"

Explanation

  • Line 2: We use require to get the set instance.
  • Line 5–8: We create some set instances and initialize them.
  • Line 11 and 12: We use the & operator to get the intersects of the sets.
  • Line 15 and 16: We print the intersects to the console in an array format.

Free Resources