Hi --

On Tue, 24 Jul 2007, bwv549 wrote:

> I have a long string and I need to know the starting position of all
> substrings matching a particular sequence.  Most importantly, it needs
> to be fast.  Secondly, it would be nice if it was somewhat concise.
>
> Here's the method:
>
> def substring_positions(substring, string)
> ## fast, concise method??

Would you settle for concise? :-)

> end
>
> my_substring = 'this'
> my_string = 'this string this is a string this is it'
>
> substring_positions(my_substring, my_string)      # -> should return
> [0, 12, 29]
>
> This seems trivial to do, but looking at StringScanner, String#match,
> and String#scan, nothing simple comes to mind.  There must be a one-
> liner somewhere for this kind of thing.  I checked through facets and
> didn't see anything...

I'll get the ball rolling, though I doubt it's very efficient:

require 'enumerator'
def substring_positions(substring, string)
   string.enum_for(:scan, substring).map { $~.offset(0)[0] }
end


David

-- 
* Books:
   RAILS ROUTING (new! http://www.awprofessional.com/title/0321509242)
   RUBY FOR RAILS (http://www.manning.com/black)
* Ruby/Rails training
     & consulting:  Ruby Power and Light, LLC (http://www.rubypal.com)