0
0
Rubyprogramming~5 mins

File.readlines for line-by-line in Ruby

Choose your learning style9 modes available
Introduction

We use File.readlines to read a file one line at a time into a list. This helps us work with each line separately.

When you want to read a text file and process each line individually.
When you need to count or analyze lines in a file.
When you want to display or print each line from a file.
When you want to store all lines from a file in an array for later use.
Syntax
Ruby
lines = File.readlines('filename.txt')

This reads all lines from the file into an array called lines.

Each element in the array is a string representing one line, including the newline character \n.

Examples
This reads all lines and prints the first line.
Ruby
lines = File.readlines('example.txt')
puts lines[0]
This reads all lines and prints each line in uppercase.
Ruby
lines = File.readlines('example.txt')
lines.each { |line| puts line.upcase }
This reads all lines and removes the newline character from each line.
Ruby
lines = File.readlines('example.txt').map(&:chomp)
Sample Program

This program creates a file with three lines, reads them all, and prints each line with its number.

Ruby
File.write('sample.txt', "Hello\nWorld\nRuby")

lines = File.readlines('sample.txt')

lines.each_with_index do |line, index|
  puts "Line #{index + 1}: #{line.chomp}"
end
OutputSuccess
Important Notes

Remember that File.readlines reads the whole file at once, so it may not be good for very large files.

Use chomp to remove the newline character from each line if you don't want it.

Summary

File.readlines reads all lines from a file into an array.

Each line includes the newline character unless removed with chomp.

It is useful for simple line-by-line file processing.