From: "Jesús Gabriel y Galán" Date: 2010-07-22T16:45:21+09:00 Subject: Re: finding last line in a file On Thu, Jul 22, 2010 at 8:35 AM, Robert Klemme wrote: > On 07/22/2010 07:10 AM, Urabe Shyouhei wrote: >> >> (2010/07/22 14:08), Urabe Shyouhei wrote: >>> >>> Take a look at the doc for File.readline. >> >> Oops... typo.  I meant readlines.  With it you can do something like >> File.readlines(f).last > > This is as inefficient as using File.foreach because it will read the whole > file.  I believe Ted was looking for a more efficient solution. > > Ted, if you want to do this in Ruby and not resort to tail you can use > IO#seek to seek to the end of the file and read backwards until you have > read more than one line. I think this is the algorithm used by James Gray in Elif: http://elif.rubyforge.org/ From those docs: " gets(sep_string = $/) The second half on the Elif algorthim (see Elif::new). This method returns the next line of the File, working from the end to the beginning in reverse line order. It works by moving the file pointer backwords MAX_READ_SIZE at a time, storing seen lines in @line_buffer. Once the buffer contains at least two lines (ensuring we have seen on full line) or the file pointer reaches the head of the File, the last line from the buffer is returned. When the buffer is exhausted, this will throw nil (from the empty Array)." Jesus.