IO modes (r, w, a) in Ruby - Time & Space Complexity
When working with files in Ruby, we use different modes to read, write, or add data. Understanding how the time to complete these actions grows with file size helps us write better programs.
We want to know: how does the time to read, write, or append change as the file gets bigger?
Analyze the time complexity of the following code snippet.
# Open a file in read mode and read all lines
File.open('data.txt', 'r') do |file|
lines = file.readlines
end
# Open a file in write mode and write lines
File.open('data.txt', 'w') do |file|
file.puts("Hello World")
end
# Open a file in append mode and add a line
File.open('data.txt', 'a') do |file|
file.puts("New line")
end
This code reads all lines from a file, writes new content replacing old data, and appends a new line at the end.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Reading all lines from the file (in read mode) involves going through each line one by one.
- How many times: The reading loop runs once for each line in the file.
- Writing and appending write data once, no loops involved.
When reading, the time grows as the file gets bigger because each line is read one after another.
| Input Size (lines) | Approx. Operations |
|---|---|
| 10 | About 10 line reads |
| 100 | About 100 line reads |
| 1000 | About 1000 line reads |
Pattern observation: Reading time grows directly with the number of lines. Writing or appending a single line stays about the same time regardless of file size.
Time Complexity: O(n)
This means reading takes longer as the file grows, because it reads each line once. Writing or appending a small amount is constant time.
[X] Wrong: "Writing to a file always takes longer as the file gets bigger."
[OK] Correct: Writing with mode 'w' replaces the file, so time depends on what you write, not the old file size. Appending adds data at the end, usually quickly.
Knowing how file operations scale helps you handle data efficiently in real projects. It shows you understand how programs interact with files and manage time well.
"What if we read the file line by line instead of all at once? How would the time complexity change?"