[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: Can one use line addresses...to select a portion of file

David Vallner

12/3/2006 6:41:00 PM

Jacob, Raymond A Jr wrote:
> I would like to select a portion of a file to process like I did with
> sed.
>
> i.e. a file called Menu with the following contents:
> __McDonalds__
>
> ...
> ...
> ...(stuff deleted)
>
> _Happy_Meal__
>
> With sed I would do something like
>
> sed -n "/__McDonalds__/,/__Happy_Meal_/p" Menu
>
> I can not find anything comparable in Ruby. I may be using the wrong
> words when I searched google for ruby line address.
> Any help will be appreciated.
>
> Thank you,
> Raymond
>

For a trivial approach, and the most terse one:

lines = file.to_a
lines_to_process = lines[(lines.index("__McDonalds__\n")) ..
lines.index("__Happy_Meal__\n"))]

Requires loading the whole file into memory, can only, and several
passes through it, so the performance is probably ugly, can only handle
lines, and can't cope with regular expressions (which is why you need
the \n in the delimiters). But probably Good Enough for some applications.

A more involved solution would probably be one yielding lines between
lines that match the delimiters to a block or returning an array of them
if no block was given. The most flexible one would be "faking" an IO
object that would start at the starting pattern and then look for the
ending one as it goes, but unless you need the data without line breaks
and without the memory overhead of keeping them in memory, probably too
much bother.

David Vallner