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 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])RandomNumbers = Set.new([6, 8, 10, 4, 2])Names = Set.new(["Amaka", "Titi", "Chioma"])Workers = Set.new(["Amaka", "Chioma", "Titi"])# check equalityputs EvenNumbers == NumbersToTen # falseputs RandomNumbers == EvenNumbers # trueputs Names == Workers # true
Explanation
- Line 2: We use
requireto 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.