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.
set.member?(element)
element
: This is the element that we want to check to see if it is a member of the set
.
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
.
# 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
require
the set
class, which is responsible for using the set
and its methods in Ruby.