How to check if two sets are equal using the == operator in Ruby

Overview

A set is a collection of unordered elements without duplicates. This means that a set is a collection of unique elements. In Ruby, two sets are said to be equal when they have similar or common elements. It means both sets should have identical elements.

Syntax

set1 == set2
Syntax for checking equality of sets using == operator

Parameters

set1 and set2: We will use these two sets to check if they are equal or not.

Return value

The set has a return value which is either true or false. If the sets are equal, then a Boolean, true is returned, else a false is returned.

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])
RandomNumbers = Set.new([6, 8, 10, 4, 2])
Names = Set.new(["Amaka", "Titi", "Chioma"])
Workers = Set.new(["Amaka", "Chioma", "Titi"])
# check equality
puts EvenNumbers == NumbersToTen # false
puts RandomNumbers == EvenNumbers # true
puts Names == Workers # true

Explanation

  • Line 2: We use require to get the set class.
  • Line 5–9: We create some set instances and initialize them with some values.
  • Line 12–14: We check the sets to see if there is any equality using the == operator. We print the results to our system console.