What is string.index() in Ruby?

Overview

The string.index() method is used to get the index of any character in a string in Ruby. This method returns the first integer of the first occurrence of the given character or substring.

Syntax

str.index(substr)

Parameters

str: This is the string that calls the index() method.

substr: This is the specified substring or character whose index we want to get.

Return value

This method returns an integer value.

Code example

# create strings
str = "Edpresso"
# get index of
# substrings or characters
a = str.index("E");
b = str.index("ss");
c = str.index("p");
d = str.index("re")
# print results
puts a
puts b
puts c
puts d

Code explanation

  • Line 2: We create a string and initialize it.

  • Lines 6–9: We call the index() method to get the indices of some characters and substrings.

  • Lines 12–15: We print the results that were returned by the index() method.

Free Resources