Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine last line in Ruby

Tags:

file-io

ruby

I'm wondering how I can determine when I am on the last line of a file that I reading in. My code looks like

File.open(file_name).each do |line|
    if(someway_to_determine_last_line)
end

I noticed that there is a file.eof? method, but how would I call the method as the file is being read? Thanks!

like image 836
Phillip Whisenhunt Avatar asked Oct 23 '25 05:10

Phillip Whisenhunt


2 Answers

If you're iterating the file with each, then the last line will be passed to the block after the end-of-file is reached, because the last line is, by definition, the line ending with EOF.

So just call file.eof? in the block.

If you'd like to determine if it's the last non-empty line in the file, you'd have to implement some kind of readahead.

like image 68
Leonid Shevtsov Avatar answered Oct 24 '25 19:10

Leonid Shevtsov


Depending on what you need to do with this "last non-empty line", you might be able to do something like this:

last_line = nil
File.open(file_name).each do |line|
    last_line = line if(!line.chomp.empty?)
    # Do all sorts of other things
end
if(last_line)
    # Do things with the last non-empty line.
end
like image 22
mu is too short Avatar answered Oct 24 '25 18:10

mu is too short



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!