To find the kth index of a substring in a string in Ruby, you can use the index method with an additional argument that specifies the starting index for the search.
Here's an algorithm you can use:
count to 1.start_index to 0.index method with two arguments: the substring you are looking for and the starting index (start_index) for the search.index method returns a valid index (not nil), increment count.count equals k, return the index.index method returns nil and count is still less than k, return -1 (or any other value indicating that the kth index was not found).Here's the Ruby code that implements the above algorithm:
main.rb236 chars13 linesYou can call this method with a string, a substring, and a value for k:
main.rb205 chars6 linesThis will output:
main.rb90 chars2 lines
gistlibby LogSnag