To find the index of a substring in Ruby, you can use the index
method of the String class.
In this example,
str
with a string value.index
method of str
to find the index of a specific substring within str
.index
method returns the starting index of the substring in the string.str = "Hello World"
index = str.index("World")
puts "Index of substring is: #{index}"
Index of substring is: 6
In this example,
str1
and str2
with different values.index
method of str1
to find the index of str2
within str1
.index
method returns the starting index of str2
in str1
.str1 = "apple banana cherry banana"
str2 = "cherry"
index = str1.index(str2)
puts "Index of substring is: #{index}"
Index of substring is: 13
In this tutorial, we learned How to find the Index of Substring in Ruby language with well detailed examples.