Q:

Ruby program to perform intersection between sets using \'&\' operator

belongs to collection: Ruby Set Programs

0

In this program, we will create two objects of the Set class and add items into created sets. Then we will perform an intersection operation between created sets using the "&" operator.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to perform set intersection between sets using the "&" operator is given below. The given program is compiled and executed successfully.

# Ruby program to perform intersection between sets 
# using '&' operator

require 'set';

setObj1 = Set.new();
setObj2 = Set.new();

setObj1.add(101);
setObj1.add(102);
setObj1.add(103);
setObj1.add(104);
setObj1.add(105);

setObj2.add(103);
setObj2.add(104);
setObj2.add(105);

setIntersection = setObj1 & setObj2;

puts "Set1: ";
for item in setObj1
   print item," ";
end

puts "\nSet2: ";
for item in setObj2
   print item," ";
end

puts "\nSet intersection is: ";
for item in setIntersection
   print item," ";
end

Output:

Set1: 
101 102 103 104 105 
Set2: 
103 104 105 
Set intersection is: 
103 104 105 

Explanation:

In the above program, we imported the "set" package using the "require" statement. Then we created two objects setObj1setObj2 of the Set class using the new() method and added items into created set using add() method of the Set class. After that, we performed an intersection operation between setObj1setObj2 using the "&" operator and assigned the result to the setIntersection set, and we printed the result.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Ruby program to perform set difference between set... >>
<< Ruby program to perform union operation between se...