How to read lines of a file in Ruby

后端 未结 8 1285
轮回少年
轮回少年 2020-12-02 04:16

I was trying to use the following code to read lines from a file. But when reading a file, the contents are all in one line:

line_num=0
File.open(\'xxx.txt\'         


        
8条回答
  •  执笔经年
    2020-12-02 04:43

    I'm partial to the following approach for files that have headers:

    File.open(file, "r") do |fh|
        header = fh.readline
        # Process the header
        while(line = fh.gets) != nil
            #do stuff
        end
    end
    

    This allows you to process a header line (or lines) differently than the content lines.

提交回复
热议问题