Ruby - Read a File Line by Line

1. Introduction

Reading files is a common task in programming. In Ruby, reading a file line by line is straightforward and can be very useful, especially for large files where reading the entire content into memory might not be feasible. This post will demonstrate how to read a file line by line in Ruby.

Reading a file line by line means processing a file's content one line at a time rather than loading the entire file into memory. This approach can be more memory-efficient and allows for real-time processing of each line.

2. Program Steps

1. Open the file in read mode.

2. Use a loop to iterate over each line of the file.

3. Process or display the line.

4. Close the file after reading.

3. Code Program

# Open the file in read mode
file = File.open('sample.txt', 'r')
# Read the file line by line
file.each_line do |line|
  puts line
end
# Close the file
file.close

Output:

Assuming the sample.txt file contains:
Hello, world!
Welcome to Ruby programming.
Have a great day!
The output will be:
Hello, world!
Welcome to Ruby programming.
Have a great day!

Explanation:

1. The File.open method is used to open the file in read mode.

2. The each_line method is used to iterate over each line in the file. It provides a convenient way to read a file line by line.

3. The puts method displays each line as it's read.

4. After all lines have been read and displayed, the file.close method is called to close the file.


Comments