On Fri, Aug 28, 2009 at 5:25 PM, 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?
>

Does this do what you want?

class String
  def all_indices(reg)
    tmp,idx = [],[]
    (0...self.length).each{|x| tmp[x] = self[x..-1]}
    tmp.each_with_index{|y,i| idx << i if y =~ /\A#{reg}/}
    idx
  end
end

p "this is a test string for the ts in the worldt".all_indices(/th/)
#> [0, 26, 36]


It may not be very fast for very long strings ( I didn't check).
But for strings like your example it seems OK.


Harry

-- 
A Look into Japanese Ruby List in English
http://www.kakueki.com/ruby/list.html