We have gone through the implementation of sets in Ruby. They are very similar to arrays. Now, let us see how we print the elements present in a set. There are no indexes present in the sets because sets are used to store the large elements.
Methods used:
- set.add(): This method is used to add the elements in the set. It would only add the elements which are not present in the set. You will not get an error if you try to add duplicate elements but duplicate elements will not be reflected in the set.
- set.each: This method is used to print the elements in the set. Whereas you cannot make changes in the set or in other words you cannot manipulate the set elements with the help of this method. We have got several set methods to manipulate the elements. This method will only print the elements in the forward direction.
- set.size(): This method tells the size of the set or the number of elements present in the set.
Variables used:
- vegetable: This is a set that contains the names of vegetables.
- i: This is working as a tracking variable which is telling the order of elements present in the set.
Code:
Output
Explanation:
In the above code, first, we have created a set named Vegetable. We have made use of set.add() method to add more elements in the Vegetable set. Our objective is to print the elements present in the set. We can only do this with the help of the set.each method. It can also be considered as a loop that works on specific variables in Ruby. The variable ‘n’ is receiving the elements present in the set one by one. We have employed a variable i to print the order of the elements.
need an explanation for this answer? contact us directly to get an explanation for this answer