From: Robert Klemme Date: 2009-04-30T17:26:00+09:00 Subject: Re: Random Access using IO#pos in code blocks 2009/4/30 Brian Candler : > Robert Klemme wrote: >> String#scan is likely faster than manually matching portions with >> #match.  In both versions of Ruby you can do this to get the >> /character/ offset: >> >> irb(main):001:0> s=%{foo bar baz} >> => "foo bar baz" >> irb(main):002:0> s.scan(/\w+/) { p $`.length } >> 0 >> 4 >> 8 >> => "foo bar baz" > > Well, my guess is that would be *less* efficient for large paragraphs, > since $` forces allocation of a new string containing all the text from > the start to the current point. Last time I checked the actual string buffer was shared so the overhead is just a single instance. I do have to admit though that I do not know when the object is allocated (i.e. at time of match or when referencing $`). > But that reminds me, there is a global > variable containing a MatchData object: $~ > > So you can write: > > irb(main):001:0> s=%{foo bar baz} > => "foo bar baz" > irb(main):002:0> s.scan(/\w+/) { p $~.begin(0) } > 0 > 4 > 8 > => "foo bar baz" Also a good variant! (Btw, MatchData might be even more heavyweight than a sub string.) Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/