This problem is all about finding a way to merge two sets. We have tried to find the solution with the help of two ways. Ruby is very rich in library. It has various predefined methods that are purposefully defined to fulfill some purpose. Here, for merging two sets, we can take help from the merge() method which is predefined in Ruby's library. Let us see the ways through which we are completing the task. We have two merge two sets or you can say that we have to store elements of two sets in the same or another set.
Methods used:
- Set.new: This method is used to create a new instance of Set class.
- Set.each: This method is used to fetch an individual element from the Set.
- Set.add(): Set.add method is predefined in Ruby's library which is used to add new elements in the Set.
- Set.merge(): This method is used to merge the set which is provided as the argument with the Set from which it is invoked.
Variables used:
- Vegetable: This is the first instance of Set class. It contains the name of vegetables.
- Fruits: This is the second instance of Set class. It contains the name of fruits.
- i: This variable is used to specifying the serial of the Set. It is used inside the Set.each method.
Example 1:
Output
Explanation:
In the above code, we are using the Set.each method to merge two sets. We are using multiple methods for this purpose. We are also using the Set.add() method to add the element from one Set to another one. You can also observe the Set which is getting updated is the Fruit set.
Example 2:
Output
Explanation:
In the above code, we are taking help from Set.merge() method. The task gets pretty simple and can be done in a single line. The resultant set is stored in Vegetable set. You can also do Fruits.merge (Vegetables) if you want to store the result in the Fruit set. At last, we are printing the set with the help of Set.each method.
need an explanation for this answer? contact us directly to get an explanation for this answer