How to read lines of a file in Ruby

后端 未结 8 1295
轮回少年
轮回少年 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:40

    Don't forget that if you are concerned about reading in a file that might have huge lines that could swamp your RAM during runtime, you can always read the file piece-meal. See "Why slurping a file is bad".

    File.open('file_path', 'rb') do |io|
      while chunk = io.read(16 * 1024) do
        something_with_the chunk
        # like stream it across a network
        # or write it to another file:
        # other_io.write chunk
      end
    end
    

提交回复
热议问题