How to get a particular line from a file

def get_line_from_file(path, line)
  result = nil

  File.open(path, "r") do |f|
    while line > 0
      line -= 1
      result = f.gets
    end
  end

  return result
end

get_line_from_file("/tmp/foo.txt", 20)

This is a good solution because:

  • You don't use File.read, thus you don't read the entire file into memory. Doing so could become a problem if the file is 20MB large and you read often enough so GC doesn't keep up.
  • You only read from the file until the line you want. If your file has 1000 lines, getting line 20 will only read the 20 first lines into Ruby.

You can replace gets with readline if you want to raise an error (EOFError) instead of returning nil when passing an out-of-bounds line.


Try one of these two solutions:

file = File.open "file.txt"

#1 solution would eat a lot of RAM
p [*file][n-1]

#2 solution would not
n.times{ file.gets }
p $_

file.close

File has a nice lineno method.

def get_line(filename, lineno)
  File.open(filename,'r') do |f|
     f.gets until f.lineno == lineno - 1
     f.gets
  end
end

You could get it by index from readlines.

line = IO.readlines("file.txt")[42]

Only use this if it's a small file.

Tags:

Ruby

File Io