On Fri, Aug 28, 2009 at 10:25 AM, timr<timrandg / gmail.com> wrote:
> In ruby you can use string#index as follows:
> str = "some text"
> str.index(/t/)
> =>5
>
> But what if I want to get all the indices for a regex in the string?
> Is there an string#all_indices method?
>
> I wrote the following, which works, but there must be a more elegant
> way:
>
> class String
>  ЁВеж бммЯйодйгеуЁтезеш©
>  ЁВодйгеу ЫЭ
>  ЁВодеш >  ЁВийме йод妦 йодеуемж®меозфЈйодеш чймм ве ойхрпо жйту> match failure, otherwise quit loop when index is equal to string
> length
>  ЁВодеш уемж®йодешЁтезешйодеш©
>  ЁВйодеш®йуЯбОхнетйЈбцпйдзеффйооййофп фийодйге> array
>  ЁВодйгеу јј йоде>  ЁВодеш «Ѕ>  ЁВод
>  ЁВод
>  ЁВодйгеу
>  ЁВод
> end
> p "this is a test string for the ts in the worldt".all_indices(/t/)
> p "what is up with all the twitter hype".all_indices(/w/)
> # >> [0, 10, 13, 16, 26, 30, 36, 45]
> # >> [0, 11, 25]
>
>
What about
class String
  def indices rgx, idx=0
    [].tap{ |r|
      loop do
        idx = index rgx, idx
        break unless idx
        r << idx
        idx += 1
      end
    }
  end
end

p "baaababbabbbba".indices( /a/ )



-- 
If you tell the truth you don't have to remember anything.
--
Samuel Clemens (some call him Mark Twain)