From: Glenn Jackman Date: 2009-08-29T01:46:01+09:00 Subject: Re: I need a string#all_indices method--is there such a thing? At 2009-08-28 04:20AM, "timr" 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? > > I wrote the following, which works, but there must be a more elegant > way: > > class String > def all_indices(regex) > indices = [] > index = 0 > while index && index < self.length #index will be nil upon first > match failure, otherwise quit loop when index is equal to string > length > index = self.index(regex, index) > if index.is_a? Numeric #avoids getting a nil into the indices > array > indices << index > index +=1 > end > end > indices > end > end > p "this is a test string for the ts in the worldt".all_indices(/t/) > p "what is up with all the twitter hype".all_indices(/w/) > # >> [0, 10, 13, 16, 26, 30, 36, 45] > # >> [0, 11, 25] This is a bit simpler: class String def all_indices(substring) idx = 0 indices = [] loop do idx = index(substring, idx) break if idx.nil? indices << idx idx += 1 end indices end end require 'test/unit' class TestAllIndices < Test::Unit::TestCase def test_it assert_equal( [0, 10, 13, 16, 26, 30, 36, 45], "this is a test string for the ts in the worldt".all_indices(/t/) ) assert_equal( [0, 11, 25], "what is up with all the twitter hype".all_indices(/w/) ) assert_equal( [12, 17, 26, 41], "the quick brown fox jumps over the lazy dog".all_indices('o') ) assert_equal( [1, 3, 5], "bananana".all_indices('ana') ) end end -- Glenn Jackman Write a wise saying and your name will live forever. -- Anonymous