From: Brian Candler Date: 2009-04-30T16:07:53+09:00 Subject: Re: Random Access using IO#pos in code blocks 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. 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" Regards, Brian. -- Posted via http://www.ruby-forum.com/.