What is the set.member?() method in Ruby?
Overview
A set is a collection of unordered unique values that cannot be duplicated. It is different from an array, which is a collection of values of the same data type and that can contain duplicates.
With the member?() method of a set, we can check if a given set contains a particular element.
Syntax
set.member?(element)
Syntax for member?() method in Ruby
Parameters
element: This is the element that we want to check to see if it is a member of the set.
Return value
The value returned is a boolean value. If the element is a member of the set, then the method returns true. Otherwise, it returns false.
Example
# require the set classrequire "set"# create some setsEvenNumbers = Set.new([2, 4, 6, 8, 10])NumbersToTen = Set.new([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])Names = Set.new(["Amaka", "Titi"])Workers = Set.new(["Amaka", "Chioma", "Titi"])EmptySet = Set.new([])# check if intersections existsputs EvenNumbers.member?(1) # falseputs Names.member?("Chioma") # falseputs Workers.member?("Chioma") # trueputs NumbersToTen.member?(5) # true
Explanation
- Line 2: We
requirethesetclass, which is responsible for using thesetand its methods in Ruby. - Lines 5–9: We create some sets.
- Lines 12–15: We check if some parameters are members of the sets we created and print the result to the console.