PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 31, 2022

[FIXED] How do I detect end of file in Ruby?

 October 31, 2022     csv, eof, parsing, ruby     No comments   

Issue

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.


Solution

https://www.ruby-forum.com/topic/218093#946117 talks about this.

content = File.read("file.txt")
content = File.readlines("file.txt")

The above 'slurps' the entire file into memory.

File.foreach("file.txt") {|line| content << line}

You can also use IO#each_line. These last two options do not read the entire file into memory. The use of the block makes this automatically close your IO object as well. There are other ways as well, IO and File classes are pretty feature rich!

I refer to IO objects, as File is a subclass of IO. I tend to use IO when I don't really need the added methods from File class for the object.

In this way you don't need to deal with EOF, Ruby will for you.

Sometimes the best handling is not to, when you really don't need to.

Of course, Ruby has a method for this.



Answered By - vgoff
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing