Coder's Cat

Ruby: How to read lines of a file


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


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

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

The document is at:

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")
#=> "This is line one\n"

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


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}"

The document is at:

Using 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.txt').read
text.each_line do |line|
print "#{number += 1} #{line}"

Join my Email List for more insights, It's Free!😋

Tags: Misc