How to Use File.readlines in Ruby: Simple Guide
In Ruby,
File.readlines reads all lines from a file and returns them as an array of strings. Each element in the array represents one line from the file, including the newline character at the end.Syntax
The basic syntax of File.readlines is simple:
File.readlines(filename, chomp: true/false)
Here, filename is the path to the file you want to read.
The optional chomp: keyword argument removes newline characters if set to true.
ruby
lines = File.readlines('example.txt', chomp: true)
Example
This example reads all lines from a file named example.txt and prints each line without the newline character.
ruby
File.write('example.txt', "Hello\nWorld\nRuby\n") lines = File.readlines('example.txt', chomp: true) lines.each do |line| puts line end
Output
Hello
World
Ruby
Common Pitfalls
One common mistake is forgetting that File.readlines includes newline characters at the end of each line by default. This can cause unexpected output when printing or processing lines.
Another pitfall is not handling file not found errors, which will raise an exception if the file does not exist.
ruby
begin lines = File.readlines('missing.txt') rescue Errno::ENOENT puts 'File not found!' end # Wrong way (includes newlines): lines = File.readlines('example.txt') puts lines # Right way (remove newlines): lines = File.readlines('example.txt', chomp: true) puts lines
Output
File not found!
Hello
World
Ruby
Hello
World
Ruby
Quick Reference
| Feature | Description |
|---|---|
| File.readlines(filename) | Reads all lines into an array with newlines included |
| File.readlines(filename, chomp: true) | Reads all lines and removes trailing newlines |
| Returns | Array of strings, each string is a line from the file |
| Raises | Errno::ENOENT if file does not exist |
| Use case | Quickly read entire file line by line for processing |
Key Takeaways
File.readlines reads all lines from a file into an array of strings.
Use the chomp: true option to remove newline characters from each line.
Handle file not found errors to avoid program crashes.
Each array element corresponds to one line in the file.
File.readlines is useful for simple line-by-line file reading.