Kernel#readlines
ios.readlines(separator=$/) -> [string] Array · Updated March 13, 2026 · Kernel Methods The readlines method reads the entire contents of an IO object (including files) and returns all lines as an array. Each line is a separate string element in the returned array, with the line separator removed by default.
How It Works
When you call readlines on a file or IO object, Ruby reads through the entire file from the current position to the end, splitting the content into lines and returning them as an array. This is equivalent to calling each_line.to_a but more concise.
Practical Examples
Reading Entire File at Once
# Read all lines from a file
lines = File.readlines("data.txt")
puts lines[0] # First line
puts lines.length # Number of lines
# Process each line
lines.each { |line| puts line.upcase }
With Custom Separator
# Read lines separated by commas (CSV-like)
csv_content = "apple,banana,cherry\norange,grape,mango"
lines = csv_content.readlines(",")
# => ["apple", "banana", "cherry\n", "orange", "grape", "mango"]
# Read paragraphs (separated by double newlines)
paragraphs = File.readlines("document.txt", "")
Reading from Standard Input
# Read all lines from stdin until EOF
puts "Enter lines (Ctrl+D to end):"
lines = STDIN.readlines
puts "You entered #{lines.length} lines"
Processing Log Files
# Analyze log file
log_lines = File.readlines("application.log")
# Find all error entries
errors = log_lines.select { |line| line.include?("ERROR") }
puts "Found #{errors.length} errors"
# Find lines after a timestamp
critical = log_lines.select { |line| line.match?(/CRITICAL/) }
Practical Data Processing
# Process CSV-like data
data = File.readlines("data.txt")
parsed = data.map do |line|
line.chomp.split(",")
end
# Filter and transform
results = File.readlines("input.txt")
.reject { |line| line.start_with?("#") } # Skip comments
.map(&:strip)
.reject(&:empty?)
Memory Considerations
readlines loads the entire file into memory, which can be problematic for very large files. For large files, consider using each_line instead:
# Memory-efficient alternative for large files
File.open("huge_file.txt", "r") do |file|
file.each_line do |line|
process(line)
end
end
Performance Tips
# Specify separator for better performance when you know the format
lines = File.readlines("file.txt", chomp: true) # Ruby 2.5+
# Use encoding when dealing with non-UTF8 files
lines = File.readlines("file.txt", encoding: "ISO-8859-1")
The readlines method is a convenient way to work with file contents when you need all lines in memory at once, making it ideal for files that fit comfortably in memory.