Array.include? / index / find_index
Methods for checking whether an array contains a specific element, or for retrieving the index of that element.
Syntax
# Checks whether the array contains the value.
array.include?(value)
# Returns the index of the first element that matches the condition.
array.index(value)
array.index { |element| condition }
# Alias for index.
array.find_index(value)
array.find_index { |element| condition }
# Returns the index of the last element that matches the condition.
array.rindex(value)
array.rindex { |element| condition }
Method List
| Method | Description |
|---|---|
| include?(val) | Returns true if the array contains the specified value, or false if it does not. |
| index(val) | Returns the index of the first matching element. Returns nil if not found. |
| index { |e| ... } | Returns the index of the first element for which the block condition is true. |
| find_index | An alias for index. Behaves identically. |
| rindex(val) | Returns the index of the last matching element. Returns nil if not found. |
Sample Code
fruits = ["apple", "banana", "orange", "banana", "grape"]
# Use include? to check for existence.
puts fruits.include?("banana") # true
puts fruits.include?("melon") # false
# Use index to get the index of the first match.
puts fruits.index("banana") # 1
puts fruits.index("melon").inspect # nil (not found)
# Use a block for condition-based searching.
numbers = [10, 25, 3, 47, 8]
puts numbers.index { |n| n > 20 } # 1 (25 matches first)
puts numbers.find_index { |n| n > 20 } # 1 (same result)
# Use rindex to get the index of the last match.
puts fruits.rindex("banana") # 3
# Use the index to retrieve an element.
idx = fruits.index("orange")
if idx
puts "orange is at index #{idx}." # orange is at index 2.
end
# Find the position of the first element meeting a condition.
scores = [65, 82, 91, 78, 55]
passing_score = 80
first_pass = scores.index { |score| score >= passing_score }
puts "First passing index: #{first_pass}" # First passing index: 1
Notes
Use include? when you only need to check whether an element exists. When you need the position (index), use index or find_index. Both behave identically, but find_index can make the intent clearer when used with a block.
index and rindex return nil when no match is found. Always check for nil before using the return value in arithmetic or other operations.
To retrieve the matching elements themselves, use select / find. To count matching elements, use count.
If you find any errors or copyright issues, please contact us.