I need a string#all_indices method--is there such a thing?

Joel VanderWerf wrote:

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/)

and this variant counts overlaps:

p "banana".all_indexes(/(?=ana)/)

···

--
       vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407

Hi --

···

On Sat, 29 Aug 2009, Joel VanderWerf wrote:

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

Just to add to the collection: there's also $~.offset(1)[0]

David

--
David A. Black / Ruby Power and Light, LLC / http://www.rubypal.com
Ruby/Rails training, mentoring, consulting, code-review
Latest book: The Well-Grounded Rubyist (http://www.manning.com/black2\)

September Ruby training in NJ has been POSTPONED. Details to follow.