What is difference() method of a set in Ruby?
Overview
The difference() method of a set in Ruby is used to find the difference between two sets. This method returns a new set by duplicating the set that invokes it and by removing each of its elements that are also present in the other set. For example, if setA has the elements [1,2,3] and setB has the elements [2,3] and the `difference()` method is invoked with setA and setB as parameters, the returned result will be [1].
Syntax
set1.difference(set2)
Syntax of the "difference()" method
Parameter values
set1: This is the set that is duplicated and has its elements removed if they are also found in the other set,set2.
set2: This is the set we want to compare with the setset1.
Return value
The difference() method returns a new set that is a duplicate of set1.
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])Names = Set.new(["Amaka", "Titi"])Workers = Set.new(["Amaka", "Chioma", "Titi"])# get the differencedifference1 = NumbersToTen.difference(EvenNumbers)difference2 = Workers.difference(Names)# print out intersectsputs "#{difference1.to_a}"puts "#{difference2.to_a}"
Explanation
- Line 2: We require the
setclass. - Lines 5–8: We create some set instances and initialize them.
- Lines 11–12: We get the differences between some sets and store them in new variables.
- Lines 15–16: We print these differences to the console.