How to Use the Ruby index Method

09/25/2021

Contents

In this article, you will learn how to use the Ruby index method.

Using the index method

Syntax

The basic syntax for the index method in Ruby is as follows:

string_or_array.index(search_term, starting_index)

Here, string_or_array refers to the string or array that you want to search, search_term is the element or substring you’re searching for, and starting_index is the index at which you want to start the search. The starting_index argument is optional and defaults to 0.

The index method returns the index of the first occurrence of the search term in the string or array, or nil if the search term is not found.

Examples

Searching a string

str = "Hello, world!"

index = str.index("o")
puts index # Output: 4

index = str.index("world")
puts index # Output: 7

index = str.index("z")
puts index # Output: nil

In this example, we have a string str that contains the text “Hello, world!”. We use the index method to search for the letter “o” in the string, and it returns the index of the first occurrence of “o”, which is 4. We then search for the substring “world” in the string, and it returns the index of the first occurrence of the substring, which is 7. Finally, we search for the letter “z” which is not present in the string, so the method returns nil.

Searching an array

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

index = arr.index(3)
puts index # Output: 2

index = arr.index(6)
puts index # Output: nil

In this example, we have an array arr that contains the numbers 1 to 5. We use the index method to search for the number 3 in the array, and it returns the index of the first occurrence of 3, which is 2. We then search for the number 6 which is not present in the array, so the method returns nil.

Specifying a starting index

str = "Hello, world!"

index = str.index("o", 5)
puts index # Output: 8

In this example, we specify a starting index of 5 for the index method. This means that the method will start searching for the search term “o” at index 5 instead of the beginning of the string. In this case, the first occurrence of “o” after index 5 is at index 8, so the method returns 8.