Leslie Viljoen
3/22/2007 8:57:00 PM
On 3/22/07, Phrogz <gavin@refinery.com> wrote:
> On Mar 22, 9:15 am, "Leslie Viljoen" <leslievilj...@gmail.com> wrote:
> > You could change your lines into an array of lines and then remove the
> > lines that match:
> >
> > lines = []
> > File.new("text.txt").read.each_line {|line| lines << line }
> > lines.delete_if {|line| line =~ /\/usr\/local\/lib/}
>
> Leslie, as a public service announcement, you should be aware of
> IO.readlines:
>
> C:\>qri IO.readlines
> ----------------------------------------------------------
> IO::readlines
> IO.readlines(name, sep_string=$/) => array
> ------------------------------------------------------------------------
> Reads the entire file specified by _name_ as individual lines,
> and
> returns those lines in an array. Lines are separated by
> _sep_string_.
>
> a = IO.readlines("testfile")
> a[0] #=> "This is line one\n"
>
>
> For that matter, you should also be aware of IO.read:
> ---------------------------------------------------------------
> IO::read
> IO.read(name, [length [, offset]] ) => string
> ------------------------------------------------------------------------
> Opens the file, optionally seeks to the given offset, then
> returns
> _length_ bytes (defaulting to the rest of the file). +read+
> ensures
> the file is closed before returning.
>
> IO.read("testfile") #=> "This is line one\nThis is
> line two\nThis is line three\nAnd so on...\n"
> IO.read("testfile", 20) #=> "This is line one\nThi"
> IO.read("testfile", 20, 10) #=> "ne one\nThis is line "
>
> You should also be aware of the block form of #open, which opens the
> IO object and then closes it when done.
>
> What you wrote creates a new File object and opens it, but never
> closes it. I'm not really sure what badness can result from this, but
> I gather it's not a good idea.
This does sound rather frightening! What *is* the effect of opening a
file and not closing it?
;-)
Also, doesn't the above say that IO.read closes the file afterwards?
--
If you could create a machine that copies hamburgers — you put one
hamburger in and two equally good hamburgers come out the other side —
it would be unethical not to do so and make it freely available.