Ruby has various specific methods to fulfil specific tasks. At several places, you may need to replace or delete an element from an instance of set class provided that there are certain elements present in the Set. You can perform deletion operation with the help of Set.delete method and if we talk about the replacement of an element, we take help from Set.replace method. In this tutorial, you will find codes through which you can find the solutions to the problem.
- The first program will tell you the way to replace an element from the Set.
- The second program will tell you the way to delete an element from the Set.
Methods used:
- Set.merge: This method is used to merge two sets.
- ===: With the help of this operator we can check the presence of an element in the set.
- Set.replace: With the help of this method, we can replace an element with a new element in the specific set.
- Set.delete: This method is used to delete an element from the set.
Variables used:
- Vegetable: This is an instance of Set class.
- Fruits: This is an instance of Set class.
Program 1:
Output
Explanation:
In the above code, you can observe that we are first merging two sets. We are then asking the user for the element which he or she wants to replace. If the element is present in the set then the replacement will take place. We are using === operator to check the presence of an element in the Set. If the presence of element comes out to be true then the user is asked for the new element and the old element is replaced with the new element.
Program 2:
Output
Explanation:
In the above code first, we have merged two Sets. We are asking the user for the element which he or she wants to delete. First, we are checking whether the element is present or not with the help of === operator. We can also use Set.include?() method for this purpose. If we find that element is present, we delete it with the help of the Set.delete method.
need an explanation for this answer? contact us directly to get an explanation for this answer