In this program, we will see how we can combine the two sets? This is not a very difficult task. This can be easily done with the help of the + operator. In many places of programming, you will find that + operator is overloaded for various types to meet various purposes. Here in the case of sets, + operator works likes arithmetic OR. It combines all the elements from both the sets and returns a set that contains all those elements. Let us look at the code and understand how we can complete this task.
Methods used:
- + : In ruby, most of the operators are considered as methods. This operator or method is used to combine two sets provided as arguments to the method. The return type of this operator is set itself. The set returned is having all the elements which are present in both the sets. Syntax:
SetA + SetB
- set.each :- set.each method is used to print the elements from the set one by one. It will provide you elements in the forward direction.
Variables used:
- Vegetable : It is an instance of Set class. It is the first argument passed as the argument in + operator.
- Sabzi : It is an instance of Set class. It is the second argument that is passed in + operator.
- New_set : It is containing the set which is returned from the + operator or method.
Program:
Output
Explanation:
In the above code, it is shown how one can combine all the elements from both the sets? As you can see above, we have defined three sets, two sets are for carrying out the processing and one set is for storing the common elements from both the sets. We have taken help from the set.each method to print all the elements from the new set. As a result, you can observe that there is no repetition of elements. It is having all the elements and each element is present only for one time. Elements are appearing single even if they are present in both sets.
need an explanation for this answer? contact us directly to get an explanation for this answer