Reading the previous line of a file using Ruby
There are several ways, it depends on how much information you have at your disposal. If you know the length of the last line you read, you can use the simplest way, which would be
# assume f is the File object
len = last_line_length
f.seek -len, IO::SEEK_CUR
Of course, if you are not provided that information becomes a little less pleasant. You can use the same approach as above to walk backwards (one byte at a time) until you hit the newline marker or grab lineno
and start reading from the beginning. Something like
lines = f.lineno f.rewind (lines - 1).times { f.gets }
However, as far as I know, there is no direct mechanism just for go back 1 N
where N
the string represents.
As an aside, you should be aware that although you can write to File.lineno
, it does not affect the position in the file, nor does it destroy the readable precision of the variable beyond that point.
source to share
Saw a great suggestion from comp.lang.ruby - use IO.tell to keep track of the position of each line in the file so you can refer to it directly:
File.open "foo" do |io|
idx = [io.tell]
while l = io.gets
p l
idx << io.tell
end
end
source to share