The question is all about to find out whether an element is present in the specified set or not? We are trying to perform this task with the help of two logics. There are lots of alternatives to a solution but here we are focusing on two alternatives only. Let us see how we find out the solution.
Methods used:
- === : This operator is an alias for .include? method and returns true or false.
- set.each : This method is used to process an individual element from the set.
- set.include?() : This method returns true or false. This is used to check the presence of an element in the set.
Variable used:
- Vegetable : This is an instance of Set class.
- element : It is containing the string which is entered by the user.
Program 1:
Output
Explanation:
In the above code, we are taking input from the user and that input is nothing but the element which we want to search. We are taking help from === operator here. With the help of this operator, we don't need to employ any kind of loop and process individual elements. Our tasks get done in a few lines of code with the help of === operator.
Program 2:
Output
Explanation:
In the above code, we are testing each element from the set and we are going to check whether it matches the element entered by the user. If it is matched with the element, the flag is set to be true. Later if the flag is found true, the string is printed on the console which informs about the presence of element and if the element is not present, a message is printed on the console which tells the element is not available.
Program 3:
Output
Explanation:
In the above code, we are employing set.include? method to check the presence of the element which is entered by the user. This makes the task pretty simple and makes our code more efficient. With the help of this method, we also reduce the line of code.
need an explanation for this answer? contact us directly to get an explanation for this answer