Posted By

jatkins on 06/27/10


index substring

Versions (?)

Find n from the index of the nth occurrence of a substring

 / Published in: Ruby

Public domain. Returns n from the nth occurrence (occurrence_index) of substring in var, or -1 if var does not contain substring or occurrence_index exceeds the length of var. Does not account for overlapping substrings (one solution is to delimit substrings, such as with a space, so you can pass " or " as substring to find occurrences of "or" as a word).

See also Find the nth occurrence of a substring.

  1. def find_n_from_occurrence_index(var, substring, occurrence_index)
  2. var = var[0..occurrence_index+substring.length]
  3. return var.include?(substring) && (occurrence_index+substring.length) <= var.length ? var.scan(substring).length : -1
  4. end

Report this snippet  

You need to login to post a comment.