How to get the difference of two sets using minus in Ruby

Overview

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.

Mathematically

A = {1, 2, 3}

B = {2, 4, 6}

A - B = {1, 2, 3} - {2, 4, 6} = {1, 3}

Syntax

set1 - set2
Syntax for the minus operator

Parameters

set 1 and set2: We'll find the difference between these two sets.

Return value

We obtain a set with a return value, which contains all the elements of set1 other than the ones in 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
difference1 = NumbersToTen - EvenNumbers
difference2 = Workers - Names
# print out intersects
puts "#{difference1.to_a}"
puts "#{difference2.to_a}"

Explanation

  • Line 2: We use require to obtain the set class.
  • Line 5–8: We create new set instances and initialize them.
  • Line 11 and 12: We obtain the difference between some sets and save the result to some new variable.
  • Line 15 and 16: We then print the differences to the console.
Note: if you change the position of the parameters then you will get the empty set, for example, EvenNumbers - NumbersToTen and Names - Workers will give us the empty set.

Free Resources