Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detect end of file in Ruby?

I wrote the following script to read a CSV file:

f = File.open("aFile.csv")
text = f.read
text.each_line do |line|
  if (f.eof?)
    puts "End of file reached"
  else
    line_num +=1
    if(line_num < 6) then
      puts "____SKIPPED LINE____"
      next
    end
  end

  arr = line.split(",")
  puts "line number  = #{line_num}" 
end

This code runs fine if I take out the line:

 if (f.eof?)
     puts "End of file reached"

With this line in I get an exception.

I was wondering how I can detect the end of file in the code above.

like image 987
banditKing Avatar asked Dec 21 '22 03:12

banditKing


1 Answers

Try this short example:

f = File.open(__FILE__)
text = f.read
p f.eof?      # -> true
p text.class #-> String

With f.read you read the whole file into text and reach EOF. (Remark: __FILE__ is the script file itself. You may use you csv-file).

In your code you use text.each_line. This executes each_line for the string text. It has no effect on f.

You could use File#each_line without using a variable text. The test for EOF is not necessary. each_line loops on each line and detects EOF on its own.

f = File.open(__FILE__)
line_num = 0
f.each_line do |line|
  line_num +=1
  if (line_num < 6) 
     puts "____SKIPPED LINE____"
     next
  end

  arr = line.split(",")
  puts "line number  = #{line_num}" 
end
f.close

You should close the file after reading it. To use blocks for this is more Ruby-like:

line_num = 0
File.open(__FILE__) do | f|
  f.each_line do |line|
    line_num +=1
    if (line_num < 6) 
       puts "____SKIPPED LINE____"
       next
  end

    arr = line.split(",")
    puts "line number  = #{line_num}" 
  end
end

One general remark: There is a CSV library in Ruby. Normally it is better to use that.

like image 121
knut Avatar answered Dec 27 '22 18:12

knut