Is there a way to seek through a file without loading the whole thing into an array?

前端 未结 3 612
执念已碎
执念已碎 2021-01-05 15:54

This works:

f = File.new(\"myfile\").readlines
f[0] #=> \"line 1\"
f[21] #=> \"line 22\"

But what if I have a very large file, and on

3条回答
  •  长发绾君心
    2021-01-05 16:18

    For the purpose you can use the each_line iterator, combined with with_index to have the line number of the current line (counting from 0):

    File.open('myfile') do |file|
    
      file.each_line.with_index do |line, lineno|
        case lineno
        when 0
          # line 1
        when 21
          # line 22
        end   
      end
    
    end
    

    By using open, passing a block to it, instead of new, you are guaranteed that the file is properly closed at the end of the block execution.


    Update The with_index method accepts an optional argument to specify the starting index to use, so che code above could be better written like this:

    file.each_line.with_index(1) do |line, lineno|
      case lineno
      when 1
        # line 1
      end
    end
    

提交回复
热议问题