OneBite.Dev - Coding blog in a bite size

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

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

s = "Hello World!"
subStr = "World"

pos = s.index(subStr)
puts pos

# Outputs 6

This code snippet uses the index method in Ruby to find the position of a substring, in this case “World”, within a larger string, in this case “Hello World!“. The index method takes a substring as a parameter and returns the index (position) of the first occurrence of the substring within the string. After the variables s and subStr are declared, the index method is called on the string s with the argument subStr. The position is then stored in the pos variable and is printed to the console with the puts command. In this example, the puts pos command will output 6 to the console, since “World” starts at the 6th letter in “Hello World!”

ruby