Ruby is very rich in the library. It has various methods for meeting specific functionalities. In Ruby, operators are basically methods with two arguments generally. We have gone through the description of sets in Ruby. We have seen their implementation also. In sets, & operator works similarly to arithmetic and you can say that it takes two sets as arguments and finds the common elements or the repeated elements from both the sets. The return type of this method is a set and that set contains all the elements which are common in both the sets.
Methods used:
- & : In ruby, most of the operators are considered as methods. This operator or method is used to find out the common elements from the sets provided as arguments to the method. The return type of this operator is set itself.
- 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 which 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 find the common elements from both 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 common in both the sets.
need an explanation for this answer? contact us directly to get an explanation for this answer