How to Check if Array Includes Element in Ruby
In Ruby, you can check if an array contains a specific element using the
include? method. It returns true if the element is found, otherwise false. For example, [1, 2, 3].include?(2) returns true.Syntax
The include? method is called on an array and takes one argument, the element you want to check for. It returns a boolean value: true if the element is present, false if not.
array.include?(element)
Here, array is your array, and element is the item you want to find.
ruby
array.include?(element)
Example
This example shows how to check if the number 3 is in the array. It prints true if found, otherwise false.
ruby
numbers = [1, 2, 3, 4, 5] puts numbers.include?(3) # true puts numbers.include?(6) # false
Output
true
false
Common Pitfalls
One common mistake is confusing include? with methods that check for indexes or keys, which do not work the same way. Also, remember that include? checks for exact matches, so "3" (string) is different from 3 (number).
Example of a wrong check and the correct way:
ruby
# Wrong: checking if index exists arr = [1, 2, 3] puts arr.include?(1) # true, checks value, not index puts arr.include?("1") # false, string vs integer # Correct: use include? for values only puts arr.include?(1) # true puts arr.include?("1") # false
Output
true
false
true
false
Quick Reference
| Method | Description | Returns |
|---|---|---|
| include?(element) | Checks if element is in array | true or false |
| index(element) | Returns index of element or nil | Integer or nil |
| member?(element) | Alias for include? | true or false |
Key Takeaways
Use
include? to check if an array contains a specific element.include? returns true if the element is found, false otherwise.The method checks for exact matches, so data types must match.
Avoid confusing
include? with methods that check indexes or keys.You can also use
member? as an alias for include?.