How to read in only the last line of a file, in pure ruby, no external commands or libraries

Hi,

My question is this:

How to read in only the last line of a file, in pure ruby, no external
commands or libraries?

That means no full read-in of the whole file.

So no .readlines() call and similar.

I was told that I can use IO#seek to seek to the last
position, then probably find the first occurance of \n
there (seeking in the other direction; I am unsure how
to do that actually, what if I read in through the
first \n there?).

But how to do this in a simple fashion?

I’d then like to customize File, through a:

File.read_last_line_of(‘foo.txt’)

Which would very quickly give me only the last line,
delimiter being \n.

f = File.open(‘data.txt’)
f.seek(-2, IO::SEEK_END) #pos -1 is newline at end of file
last_line = nil

while f.pos > 0
if f.getc == “\n”
last_line = f.read
break
else
f.pos -= 2 #getc advances position by 1
end
end

if last_line
puts last_line
else
puts f.read
end

f.close

However, the simplest thing to do is:

last_line = nil

IO.foreach(‘data.txt’) do |line|
last_line = line
end

puts last_line

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs