File.readlines for line-by-line in Ruby - Time & Space Complexity
When reading a file line by line using File.readlines, it's important to know how the time to read grows as the file gets bigger.
We want to understand how the number of lines affects the time it takes to read them all.
Analyze the time complexity of the following code snippet.
lines = File.readlines("example.txt")
lines.each do |line|
puts line.strip
end
This code reads all lines from a file into an array, then goes through each line to print it without extra spaces.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Reading each line from the file and then iterating over each line.
- How many times: Once for each line in the file.
As the number of lines grows, the time to read and process them grows roughly the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 reads and 10 prints |
| 100 | About 100 reads and 100 prints |
| 1000 | About 1000 reads and 1000 prints |
Pattern observation: The work grows directly with the number of lines; double the lines, double the work.
Time Complexity: O(n)
This means the time to read and process the file grows in a straight line with the number of lines.
[X] Wrong: "Reading lines with File.readlines is instant no matter the file size."
[OK] Correct: Reading each line takes time, so bigger files take longer to read line by line.
Understanding how file reading scales helps you write programs that handle big files without surprises.
"What if we used File.foreach instead of File.readlines? How would the time complexity change?"