We know the way to declare the instance of the set class in Ruby. Most of the time, we may need to find the length of the set or you can say that we may need to find the number of elements in the specific set. Ruby is very rich in library and it provides you a method known as Set.length() method which returns the number of elements present in the Set. But, we should know how to solve things without method also? We will focus on two ways through which we can find the length of the Set. The first one is without using method and the second one is with the help of the method.
Methods used:
- Set.each: It is used to traverse the set. It processes the elements of the set one by one.
- Set.length: This method is a predefined method in Ruby’s library which is purposefully defined to find the number of elements present in the set. The return type of this method is an integer which is equivalent to the length of the set from which it has been invoked.
- Set.merge: This method merges two sets and stores the resultant set in that set from which it has been invoked. The return type of this method is Set.
Variables used:
- Vegetable: This is an instance of Set class.
- Fruits: This is an instance of Set class.
- Count: It is acting as a counter variable. It is counting the number of elements present in the Set.
Example 1:
Output
Explanation:
In the above code, we are trying to find the length of the resultant set. First, we have declared two sets and then carrying out the merging process. We are passing the elements of a resultant set into Set.each loop. Inside Set.each loop, we are incrementing the count variable by 1. count variable is initialized with 0. At last, we are getting the number of elements present in the set.
Example 2:
Output
Explanation:
In the above code, we have declared two instances or objects of Set class. We are first merging them and storing the result in the Vegetable set. We are then finding the length of the resultant set with the help of Set.length method which is a predefined method in Ruby.
need an explanation for this answer? contact us directly to get an explanation for this answer