Get index of string scan results in ruby
There's a gotcha to look out for here, depending on the behaviour you expect.
If you search for /dad/
in "dadad"
you'd only get [["dad",0]]
because scan
advances to the end of each match when it finds one (which is wrong to me).
I came up with this alternative:
def scan_str(str, pattern) res = [] (0..str.length).each do |i| res << [Regexp.last_match.to_s, i] if str[i..-1] =~ /^#{pattern}/ end resend
If you wanted you could also do a similar thing with StringScanner from the standard library, it might be faster for long strings.