How to read lines of a file in Ruby

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

    Ruby does have a method for this:

    File.readlines('foo').each do |line|
    

    http://ruby-doc.org/core-1.9.3/IO.html#method-c-readlines

    0 讨论(0)
  • 2020-12-02 04:40
    File.foreach(filename).with_index do |line, line_num|
       puts "#{line_num}: #{line}"
    end
    

    This will execute the given block for each line in the file without slurping the entire file into memory. See: IO::foreach.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-02 04:43

    how about gets ?

    myFile=File.open("paths_to_file","r")
    while(line=myFile.gets)
     //do stuff with line
    end
    
    0 讨论(0)
  • 2020-12-02 04:55

    It is because of the endlines in each lines. Use the chomp method in ruby to delete the endline '\n' or 'r' at the end.

    line_num=0
    File.open('xxx.txt').each do |line|
      print "#{line_num += 1} #{line.chomp}"
    end
    
    0 讨论(0)
提交回复
热议问题