find the last index of a substring in a string in ruby

To find the last index of a substring in a string in Ruby, you can use the String#rindex method. This method returns the index of the last occurrence of the specified substring, or nil if the substring is not found.

Here's an example:

main.rb
string = "hello world"
substring = "l"

last_index = string.rindex(substring)

puts last_index    # Output: 9
110 chars
7 lines

In this example, the rindex method is called on the string variable with the substring variable passed as an argument. The method returns the index of the last occurrence of the substring "l", which is 9. The puts statement prints the value of the last_index variable to the console.

gistlibby LogSnag