Ruby: How to read lines of a file

  • Misc

In this tutorial, I will show how to read lines from files, with the consideration of performance.

File.readlines

There is a function called File.readlines in Ruby’s standard library, the usage is:

File.readlines('file.txt').each do |line|
   ....
end

The document is at: https://ruby-doc.org/core-2.7.0/IO.html#method-c-readlines

Note 1: readlines will load the entire file into memory firstly, so it maybe performs badly on the large files.

Note 2: By default readlines still keep the \n in the lines, if you want to drop the last \n, you could pass a chmop: true parameter:

a = IO.readlines("file.txt")
a[0]   
#=> "This is line one\n"

b = IO.readlines("file.txt", chomp: true)
b[0]   
#=> "This is line one"

IO.foreach

Another function named IO.foreach will not load the entire file into memory, instead read by chunks.

File.foreach(filename).with_index do |line, line_no|
   puts "#{line_no}: #{line}"
end

The document is at: https://ruby-doc.org/core-2.7.0/IO.html#method-c-foreach

Using File.read and then split into lines

Another method is to read the content into one buffer and then split it into lines.

Note different OS use different line format, Unix uses \n, Windows \r\n, MacOs uses \n

number = 0
text = File.open('file.txt').read
text.gsub!(/(\r|\n)+/,"\n")  
text.each_line do |line|
  print "#{number += 1} #{line}"
end
Last Updated on
Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *