0
0
RubyHow-ToBeginner · 3 min read

How to Find Index of Element in Array Ruby - Simple Guide

In Ruby, you can find the index of an element in an array using the index method. It returns the position of the first matching element or nil if the element is not found.
📐

Syntax

The basic syntax to find the index of an element in a Ruby array is:

  • array.index(element) - Returns the index of the first occurrence of element in array.
  • If the element is not found, it returns nil.
ruby
array.index(element)
💻

Example

This example shows how to find the index of the element "apple" in an array of fruits. It also shows what happens if the element is not found.

ruby
fruits = ["banana", "apple", "orange", "apple"]
index_apple = fruits.index("apple")
index_grape = fruits.index("grape")

puts "Index of 'apple': #{index_apple}"
puts "Index of 'grape': #{index_grape.inspect}"
Output
Index of 'apple': 1 Index of 'grape': nil
⚠️

Common Pitfalls

One common mistake is expecting index to return all positions of an element if it appears multiple times. It only returns the first match.

Also, if the element is not found, index returns nil, so be careful when using the result directly without checking.

ruby
arr = [1, 2, 3, 2, 4]

# Wrong: expecting all indexes
all_indexes = arr.index(2)  # returns only first index 1

# Right: to find all indexes, use each_with_index
all_indexes_correct = arr.each_with_index.select { |val, idx| val == 2 }.map(&:last)

puts "First index of 2: #{all_indexes}"
puts "All indexes of 2: #{all_indexes_correct}"
Output
First index of 2: 1 All indexes of 2: [1, 3]
📊

Quick Reference

MethodDescriptionReturn Value
index(element)Returns first index of elementInteger or nil if not found
each_with_index + selectFinds all indexes of elementArray of indexes
rindex(element)Returns last index of elementInteger or nil if not found

Key Takeaways

Use array.index(element) to get the first index of an element in a Ruby array.
If the element is not found, index returns nil, so check before using the result.
To find all indexes of an element, combine each_with_index with select and map.
Remember index only returns the first occurrence, not all.
Use rindex to find the last occurrence index of an element.