OneBite.Dev - Coding blog in a bite size

find the position of the last occurrence of a substring in a string in Ruby

Code snippet on how to find the position of the last occurrence of a substring in a string in Ruby

  str = "Hello World"
  puts str.rindex("o")

This code will find the position of the last occurrence of a substring in a given string. First, the code declares a string called “str” and assigns it the value “Hello World”. Then, it uses the rindex method, which locates the last occurrence of a given string within the declared string. In this case, it searches for the substring “o”, and the code returns the position of the last “o” in the string, which is 9. Finally, it prints out the result using the puts method.

ruby