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?"
Practice
File.readlines('example.txt') return in Ruby?Solution
Step 1: Understand File.readlines behavior
File.readlinesreads the whole file and returns an array of lines.Step 2: Check line content format
Each line includes the newline character at the end unless removed bychomp.Final Answer:
An array where each element is a line from the file, including newline characters -> Option CQuick Check:
File.readlines returns array of lines [OK]
- Thinking it returns a single string
- Assuming it returns a hash or dictionary
- Believing it returns just the line count
data.txt into an array in Ruby?Solution
Step 1: Recall correct method name
The correct Ruby method to read lines isFile.readlines(no underscore or plural misspelling).Step 2: Check method call syntax
The method is called with parentheses and the filename as a string argument.Final Answer:
File.readlines('data.txt') -> Option DQuick Check:
Correct method name and syntax = File.readlines('data.txt') [OK]
- Using underscores instead of camel case
- Misspelling the method name
- Omitting parentheses or using wrong brackets
notes.txt with these lines:Line 1 Line 2 Line 3
What will the following Ruby code output?
lines = File.readlines('notes.txt')
puts lines[1]Solution
Step 1: Understand File.readlines output
The file lines are read into an array: ["Line 1\n", "Line 2\n", "Line 3\n"].Step 2: Access the second element
Array indexing starts at 0, solines[1]is "Line 2\n".Final Answer:
Line 2 -> Option AQuick Check:
Index 1 = second line = Line 2 [OK]
- Assuming indexing starts at 1
- Forgetting newline characters affect output
- Expecting nil for valid index
lines = File.readlines('file.txt')
lines.each do |line|
puts line.chomp
endAssuming
file.txt exists and is readable.Solution
Step 1: Analyze File.readlines usage
File.readlinesreads all lines into an array, each ending with a newline.Step 2: Check iteration and chomp usage
Usingeachto iterate andchompremoves trailing newline before printing.Final Answer:
Nothing is wrong; it correctly prints each line without newlines -> Option BQuick Check:
chomp removes newline, so output is clean [OK]
- Thinking chomp is invalid method
- Expecting extra newlines despite chomp
- Assuming lines are skipped
data.txt and create a new array containing only lines that include the word "error" (case insensitive). Which Ruby code correctly does this using File.readlines?Solution
Step 1: Use File.readlines to get all lines
This returns an array of lines from the file.Step 2: Filter lines case-insensitively
Useselectto keep lines whereline.downcase.include?('error')is true.Step 3: Check other options
File.readlines('data.txt').map { |line| line.include?('error') } usesmapwhich returns booleans, not lines. File.readlines('data.txt').filter { |line| line.include?('Error') } checks case-sensitive 'Error'. File.readlines('data.txt').reject { |line| line.downcase.include?('error') } rejects lines with 'error', opposite of requirement.Final Answer:
File.readlines('data.txt').select { |line| line.downcase.include?('error') } -> Option AQuick Check:
select + downcase + include? = correct filter [OK]
- Using map instead of select
- Ignoring case sensitivity
- Using reject instead of select
Ready to prove it?
Pass the test and this pattern moves unknown
