The set is an unordered collection with no duplicate items. Like other languages, Ruby also provides a set class that represents the mathematical notion of a set. Here, we will discuss the basic set operations, i.e., Union, Intersection, and Difference.
Union
In Ruby, the union takes two objects like arrays, vectors, hashes, etc. as arguments and results in a third object which contains all the elements from both the objects and removes duplicate elements. You can perform a union between two arrays using the pipe operator(|).
Syntax:
x | y
Parameters: x and y are the sequence items of objects.
For Example:
[1, 2, 1, 2, 3, 5, 7] | [1, 2, 3, 4] #=> [1, 2, 3, 4, 5, 7]
Example 1:
arr_1 = [ 2 , 4 , 5 , 6 , 7 , 9 , 1 , 2 , 4 ]
arr_2 = [ 2 , 4 , 5 , 6 , 9 , 8 , 0 , 3 , 3 ]
result = arr_1 | arr_2
puts "#{result}"
|
Output:
[2, 4, 5, 6, 7, 9, 1, 8, 0, 3]
Example 2:
class MultiSet
attr_accessor :set
def initialize(set)
@set = set
end
def |(other)
@set | other.set
end
end
x = MultiSet. new ([ 1 , 1 , 2 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ])
y = MultiSet. new ([ 1 , 3 , 5 , 6 , 8 ])
p x | y
|
Output:
[1, 2, 3, 4, 5, 6, 7, 8]
Intersection
In Ruby, intersection takes two objects like arrays, vectors, hashes, etc. as arguments and results in a third object which contains elements that are common in both the objects and remove duplicates. The order in the intersection is preserved from the original array. You can perform intersection either by using & operator or by using the intersection() function.
Syntax:
x & y
Parameters: x and y are the sequence items of objects.
For Example:
[ 'a', 'b', 'b', 'z' ] & [ 'a', 'b', 'c' ,'z'] #=> [ 'a', 'b' ,'z']
Example 1:
require "set"
x = Set. new ([ 1 , 2 , 3 , 4 ])
y = Set. new ([ 1 , 2 , 4 ])
res = x.intersection(y)
puts res
|
Output:
Set: {1, 2, 4}
Example 2:
class MultiSet
attr_accessor :set
def initialize(set)
@set = set
end
def &(other)
@set & other.set
end
x = MultiSet. new ([ 1 , 1 , 2 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ])
y = MultiSet. new ([ 1 , 3 , 5 , 6 , 8 ])
p x & y
end
|
Output:
[1, 3, 5, 6, 8]
Difference
In Ruby, difference takes two objects like arrays, vectors, hashes, etc. as arguments and returns the difference of both the objects. You can perform difference either by using – operator or by using the difference() function.
Syntax:
x – y
Parameters: x and y are the sequence items of objects.
For Example:
[ 22, 45, 89, 76 ] - [ 22, 22, 89, 79 ] #=> [45]
Example 1:
require "set"
x = Set. new ([ 1 , 2 , 3 , 4 ])
y = Set. new ([ 1 , 2 , 4 , 5 ])
res = x.difference(y)
puts res
|
Output:
Set: {3}
Example 2:
class MultiSet
attr_accessor :set
def initialize(set)
@set = set
end
def -(other)
@set - other.set
end
x = MultiSet. new ([ 1 , 1 , 2 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ])
y = MultiSet. new ([ 1 , 3 , 5 , 6 , 8 ])
p x - y
end
|
Output:
[2, 2, 4, 7]
Last Updated :
05 Mar, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...