To find the indices of all occurrences of a substring in Ruby, you can use the each_index
method with a block to iterate through the string and store the indices of matches.
In this example,
str
with a string value.each_index
method with a block to iterate through str
and store the indices of matches.str = "Hello Hello Hello"
substr = "Hello"
indices = []
str.chars.each_index { |i|
indices << i if str[i, substr.length] == substr
}
puts "Indices of all occurrences: #{indices}"
Indices of all occurrences: [0, 6, 12]
In this example,
str
and substr
with different values.each_index
method with a block to iterate through str
and store the indices of matches.str = "apple banana cherry banana"
substr = "banana"
indices = []
str.chars.each_index { |i|
indices << i if str[i, substr.length] == substr
}
puts "Indices of all occurrences: #{indices}"
Indices of all occurrences: [6, 20]
In this tutorial, we learned How to find the Indices of All Occurrences of Substring in Ruby language with well detailed examples.