Reading the previous line of a file using Ruby

How to read the prevailing line of a file. The opposite of IO.gets.I was originally supposed to set IO.lineno to the line number I wanted to read, but that doesn't work as expected. How do you actually read the previous line?

+2


source to share


4 answers


One easy way is to remember the previous line you are reading:



prev = nil
File.foreach('_vimrc') do |line|
  p [line, prev]  # do whatever processing here
  prev = line
end

      

+4


source


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.

+3


source


Elif gem has a get method which is the opposite of IO.gets.

$ sudo gem install elif

$ irb

require "elif"
last_syslog = Elif.open('/var/log/syslog') { |file| file.gets }

      

+1


source


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 

      

0


source







All Articles