What is the set.include?(element) in Ruby?
Overview
In Ruby, we use the include() method to check if an element is a member of a particular set. An element is said to be a set member if present in the given set. The code snippet below shows how to use the include() method.
Syntax
Set.include?(element)
This line checks if `element` is a part of `Set`.
The code snippet has two main variables: Set and element. The code tests the membership of element in Set. Set.include?(element) will return true if element is a member of Set, and false otherwise.
Example
Let’s look at an example that uses include?().
# require setrequire "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"])# check if some elements are member of a setputs EvenNumbers.include?(2) # trueputs NumbersToTen.include?(9) # trueputs Names.include?("Okwudili") # falseputs Workers.include?("Paul") # false
Explanation
- Line 2: We import the
setclass. - Lines 5–8: We create and initialize 4 set instances.
- Lines 11–14: We use the
include?()method to check if certain elements are present in the sets created previously. Results can be seen in the console shortly after pressing the run button.