Finding differences simply means that finding elements that are uncommon between two sets as well as are only present in the first set. We can find this, with the help of a – operator. You can also consider the objective as to find the unique elements from the first set or you can say that the set which is passed as the first argument.
Methods used:
- -: In ruby, most of the operators are considered as methods. This operator or method is used to find out the unique elements from the set which is provided as the first argument to the - method. The return type of this operator is a set itself.
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 a set. 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.
Code:
Output
Explanation:
In the above code, it is shown how one can find the unique elements from the first set by finding the difference 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 find that the new set contains all the elements which are not present in the second set. This method would not give you elements that are unique in the second set.
need an explanation for this answer? contact us directly to get an explanation for this answer