From: timr Date: 2009-08-29T00:05:05+09:00 Subject: Re: I need a string#all_indices method--is there such a thing? On Aug 28, 5:02 am, Harry Kakueki wrote: > > 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] > > > Harry > > Sorry, it looks like I had an unnecessary line in there. > > class String >   def all_indices(reg) >     idx = [] >     (0...self.length).each{|x| idx << x if self[x..-1] =~ /\A#{reg}/} >     idx >   end > end > > p "this is a test string for the ts in the worldt".all_indices(/th/) > #> [0, 26, 36] > p "banana".all_indices(/ana/) #> [1, 3] > > Harry > > -- > A Look into Japanese Ruby List in Englishhttp://www.kakueki.com/ruby/list.html This works and the code is more concise than what I had, but it is a brute force approach that test for matches from every possible substring. That would be a bit slow.