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.
str.index(substr)
str
: This is the string that calls the index()
method.
substr
: This is the specified substring or character whose index we want to get.
This method returns an integer value.
# create stringsstr = "Edpresso"# get index of# substrings or charactersa = str.index("E");b = str.index("ss");c = str.index("p");d = str.index("re")# print resultsputs aputs bputs cputs d
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.