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