[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Detecting the end of a text file...

sketchitup@gmail.com

7/25/2007 4:44:00 PM

I'm just beginning to learn the Ruby progamming language, although I
have some previous programming experience in Java. I would like to
know if how I can detect the end of a file when parsing a text file in
Ruby. I don't want to throw an error or exception when I reach the end
of the file, I just want to tell my parser to stop parsing.

Thanks for the help.

The SketchUp Artist

2 Answers

Luis Parravicini

7/25/2007 5:02:00 PM

0

On 7/25/07, sketchitup@gmail.com <sketchitup@gmail.com> wrote:
> I'm just beginning to learn the Ruby progamming language, although I
> have some previous programming experience in Java. I would like to
> know if how I can detect the end of a file when parsing a text file in
> Ruby. I don't want to throw an error or exception when I reach the end
> of the file, I just want to tell my parser to stop parsing.

As far as I know, all the IO methods return nil on EOF except for
readline. You could read the file with:

File.open(path) do |f|
while line=f.gets
# parse
end
end

or

File.open(path) do |f|
begin
loop do
line = f.readline
# parse
end
rescue EOFError
end

or slurp the whole file with IO.readline(path)

--
Luis Parravicini
http://ktulu.co...

sketchitup@gmail.com

7/25/2007 6:16:00 PM

0

On Jul 25, 10:02 am, "Luis Parravicini" <lparr...@gmail.com> wrote:
> On 7/25/07, sketchi...@gmail.com <sketchi...@gmail.com> wrote:
>
> > I'm just beginning to learn the Ruby progamming language, although I
> > have some previous programming experience in Java. I would like to
> > know if how I can detect the end of a file when parsing a text file in
> > Ruby. I don't want to throw an error or exception when I reach the end
> > of the file, I just want to tell my parser to stop parsing.
>
> As far as I know, all the IO methods return nil on EOF except for
> readline. You could read the file with:
>
> File.open(path) do |f|
> while line=f.gets
> # parse
> end
> end
>
> or
>
> File.open(path) do |f|
> begin
> loop do
> line = f.readline
> # parse
> end
> rescue EOFError
> end
>
> or slurp the whole file with IO.readline(path)
>
> --
> Luis Parravicinihttp://ktulu.co...

Thanks for the responses Luis. I think I need to read a little more
about errors and exceptions in Ruby before I use your examples.

Thanks,

The SketchUp Artist