Detecting the end of a text file...

S

sketchitup

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
 
L

Luis Parravicini

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)
 
S

sketchitup

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)

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top