Reading the last n lines of a file in Ruby?

前端 未结 8 1109
北荒
北荒 2020-11-30 09:59

I need to read the last 25 lines from a file (for displaying the most recent log entries). Is there anyway in Ruby to start at the end of a file and read it backwards?

8条回答
  •  星月不相逢
    2020-11-30 10:07

    I just wrote a quick implemenation with #seek:

    class File
      def tail(n)
        buffer = 1024
        idx = (size - buffer).abs
        chunks = []
        lines = 0
    
        begin
          seek(idx)
          chunk = read(buffer)
          lines += chunk.count("\n")
          chunks.unshift chunk
          idx -= buffer
        end while lines < n && pos != 0
    
        chunks.join.lines.reverse_each.take(n).reverse.join
      end
    end
    
    File.open('rpn-calculator.rb') do |f|
      p f.tail(10)
    end
    

提交回复
热议问题