From: Joel VanderWerf Date: 2009-08-29T06:08:29+09:00 Subject: Re: I need a string#all_indices method--is there such a thing? Bertram Scharpf wrote: > Hi, > > Am Freitag, 28. Aug 2009, 17:40:05 +0900 schrieb timr: >> Scan gives you the matches, not the indices (which is what I need). >> >>>> "this is a test for scan".scan(/t/) >> => ["t", "t", "t"] > > There's a trick to do it with String#scan: > > a = [] > "this is a test for scan".scan( /t/) { a.push $`.length } > a > > This does not work when the matches overlap. > > "banana".scan /ana/ #=> ["ana"] > > Bertram > > Same difficulty with overlap, but for variety: class String def all_indexes re a=[];scan(re) {a<<$~.begin(0)};a end end p "foo bar baz".all_indexes(/.../) p "banana".all_indexes(/ana/) __END__ Output: [0, 3, 6] [1] -- vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407