Created
October 12, 2018 13:47
-
-
Save a2ikm/5fa159891de7aa168b8577671ba516e3 to your computer and use it in GitHub Desktop.
nth index of pattern in Ruby's String
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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