OneBite.Dev - Coding blog in a bite size

find the index of a substring within a string in Ruby

Code snippet on how to find the index of a substring within a string in Ruby

  my_string = "The quick brown fox"
  target = "brown"
  my_string.index(target)

This code will find the index of a substring within a string. The code begins by assigning the string “The quick brown fox” to the my_string variable. Next the target string “brown” is assigned to the target variable. Lastly, the index of the target string within the my_string is retrieved by executing the my_string.index(target) command. This command searches for the target string (in this case “brown”) within my_string and returns the position of the first occurrence of the target string. In this case, the index of the target string “brown” is 11.

ruby