From: Arun Kumar Date: 2009-04-29T21:00:14+09:00 Subject: Re: Random Access using IO#pos in code blocks --001e680f08c458ff460468b05269 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: quoted-printable Thank you so much for the kind responses! I'm pleased to be part of such a kind community :) On Wed, Apr 29, 2009 at 4:32 PM, Robert Klemme wrote: > 2009/4/29 Brian Candler : > > Unfortunately, I don't think string#scan will give you offsets into the > > strings found. > > > > In ruby 1.8 you can write this: > > > > pos =3D 0 > > while md =3D /\b\w+\b/.match(para[pos..-1]) > > word =3D md[0] > > puts "Match #{word} at #{para_pos+pos+md.begin(0)}" > > pos +=3D md.end(0) > > ... > > end > > > > In ruby 1.9 (but not 1.8.6/1.8.7), Regexp.match takes a start pos, so > > you could optimise it to this: > > > > pos =3D 0 > > while md =3D /\b\w+\b/.match(para, pos) > > word =3D md[0] > > puts "Match #{word} at #{para_pos+md.begin(0)}" > > pos =3D md.end(0) > > ... > > end > > 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=3D%{foo bar baz} > =3D> "foo bar baz" > irb(main):002:0> s.scan(/\w+/) { p $`.length } > 0 > 4 > 8 > =3D> "foo bar baz" > > > However in ruby 1.9 the offsets used will be in terms of number of > > characters, not number of bytes. It would be up to you to convert this > > back into byte offsets into the file, if that's what you're after. > > This is an important point to remember! > > Kind regards > > robert > > -- > remember.guy do |as, often| as.you_can - without end > http://blog.rubybestpractices.com/ > > --=20 || =E0=A4=B6=E0=A5=8D=E0=A4=B0=E0=A5=80 =E0=A4=9C=E0=A4=BE=E0=A4=A8=E0=A4= =95=E0=A5=80=E0=A4=B0=E0=A4=98=E0=A5=81=E0=A4=A8=E0=A4=BE=E0=A4=A5=E0=A5=8B= =E0=A4=B5=E0=A4=BF=E0=A4=9C=E0=A4=AF=E0=A4=A4=E0=A5=87 || --001e680f08c458ff460468b05269--