File.open with block (auto-close) in Ruby - Time & Space Complexity
We want to understand how the time it takes to run a Ruby file operation changes as the file size grows.
Specifically, how does reading a file with File.open using a block affect the time it takes?
Analyze the time complexity of the following code snippet.
File.open('example.txt', 'r') do |file|
file.each_line do |line|
puts line
end
end
This code opens a file, reads it line by line, and prints each line. The file is automatically closed after the block finishes.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Reading each line of the file one by one.
- How many times: Once for every line in the file.
As the number of lines in the file increases, the time to read and print grows roughly in direct proportion.
| Input Size (lines) | Approx. Operations |
|---|---|
| 10 | About 10 line reads and prints |
| 100 | About 100 line reads and prints |
| 1000 | About 1000 line reads and prints |
Pattern observation: The time grows steadily as the file gets longer, roughly one step per line.
Time Complexity: O(n)
This means the time to run the code grows in a straight line with the number of lines in the file.
[X] Wrong: "Using a block with File.open makes the reading instant or constant time."
[OK] Correct: The block only helps with closing the file automatically. Reading still takes time proportional to the file size.
Understanding how file reading time grows helps you write efficient programs that handle data well, a useful skill in many coding tasks.
"What if we read the whole file at once instead of line by line? How would the time complexity change?"