# I need a string#all\_indices method--is there such a thing?

**URL:** <https://rubytalk.org/t/i-need-a-string-all-indices-method-is-there-such-a-thing/55117>\
**Category:** ruby-talk\
**Created:** [28 August 2009 08:25 UTC](https://rubytalk.org/t/i-need-a-string-all-indices-method-is-there-such-a-thing/55117 "2009-08-28T08:25:08Z")\
**Posts on this page:** 2\
**Page:** 2

<div class="post-metadata">

**Author:** ![Joel\_VanderWerf1](https://avatars.discourse-cdn.com/v4/letter/j/94ad74/32.png) [@Joel\_VanderWerf1](https://rubytalk.org/u/Joel_VanderWerf1)\
**Post date:** [28 August 2009 21:11 UTC](https://rubytalk.org/t/i-need-a-string-all-indices-method-is-there-such-a-thing/55117/21 "2009-08-28T21:11:23Z")

</div>

Joel VanderWerf wrote:

> class String  
> &nbsp;&nbsp;def all\_indexes re  
> &nbsp;&nbsp;&nbsp;&nbsp;a=;scan(re) {a\<\<$~.begin(0)};a  
> &nbsp;&nbsp;end  
> end
> 
> p "foo bar baz".all\_indexes(/.../)  
> p "banana".all\_indexes(/ana/)

and this variant counts overlaps:

p "banana".all\_indexes(/(?=ana)/)

> **···**
>
> --  
> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407

---

<div class="post-metadata">

**Author:** ![David\_A\_Black1](https://avatars.discourse-cdn.com/v4/letter/d/bcef8e/32.png) [@David\_A\_Black1](https://rubytalk.org/u/David_A_Black1)\
**Post date:** [28 August 2009 23:01 UTC](https://rubytalk.org/t/i-need-a-string-all-indices-method-is-there-such-a-thing/55117/22 "2009-08-28T23:01:17Z")

</div>

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:
> > > 
> > > &nbsp;&nbsp;a =   
> > > &nbsp;&nbsp;"this is a test for scan".scan( /t/) { a.push $`.length }  
> > > &nbsp;&nbsp;a
> > > 
> > > This does not work when the matches overlap.
> > > 
> > > &nbsp;&nbsp;"banana".scan /ana/ #=\> ["ana"]
> > > 
> > > Bertram
> > 
> > Same difficulty with overlap, but for variety:
> > 
> > class String  
> > def all\_indexes re  
> > &nbsp;&nbsp;&nbsp;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](http://www.rubypal.com)  
> Ruby/Rails training, mentoring, consulting, code-review  
> Latest book: The Well-Grounded Rubyist ([http://www.manning.com/black2\](http://www.manning.com/black2%5C))
> 
> September Ruby training in NJ has been POSTPONED. Details to follow.

[Previous page](https://rubytalk.org/t/i-need-a-string-all-indices-method-is-there-such-a-thing/55117.md?page=1)
