How to Read File Line by Line in Ruby: Simple Guide
In Ruby, you can read a file line by line using
File.foreach('filename') or by opening the file with File.open and iterating over each line with each_line. These methods let you process large files efficiently without loading the entire file into memory.Syntax
Here are two common ways to read a file line by line in Ruby:
File.foreach('filename') do |line| ... end: Reads each line one by one directly from the file.File.open('filename', 'r') do |file| file.each_line do |line| ... end end: Opens the file and iterates over each line.
Both methods yield each line as a string to the block for processing.
ruby
File.foreach('example.txt') do |line|
puts line
endExample
This example shows how to read a file named example.txt line by line and print each line to the screen.
ruby
File.foreach('example.txt') do |line|
puts line.chomp
endOutput
Hello, world!
This is a test file.
Reading line by line in Ruby.
Common Pitfalls
Common mistakes when reading files line by line include:
- Not closing the file when using
File.openwithout a block, which can cause resource leaks. - Forgetting to remove newline characters with
chomp, which can affect output formatting. - Trying to read the entire file into memory instead of line by line, which is inefficient for large files.
ruby
file = File.open('example.txt', 'r') file.each_line do |line| puts line end file.close # Correct way: File.open('example.txt', 'r') do |file| file.each_line do |line| puts line.chomp end end
Quick Reference
Summary tips for reading files line by line in Ruby:
- Use
File.foreach('filename')for simple, memory-efficient reading. - Use
File.open('filename', 'r') do |file| ... endwhen you need more control. - Always use
chompto remove newline characters if you want clean output. - Prefer block forms to ensure files are closed automatically.
Key Takeaways
Use File.foreach or File.open with each_line to read files line by line in Ruby.
Always use block form to automatically close files and avoid resource leaks.
Use chomp to remove newline characters from each line for cleaner output.
Reading line by line is memory efficient for large files compared to reading all at once.