Skip to content

Instantly share code, notes, and snippets.

@a2ikm
Created October 12, 2018 13:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save a2ikm/5fa159891de7aa168b8577671ba516e3 to your computer and use it in GitHub Desktop.
Save a2ikm/5fa159891de7aa168b8577671ba516e3 to your computer and use it in GitHub Desktop.
nth index of pattern in Ruby's String
class String
def nth_index(pattern, n)
pos = nil
offset = nil
begin
pos = index(pattern, offset || 0)
return nil if pos.nil?
n -= 1
offset = pos + 1
end while n >= 0
pos
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment