Bird
Raised Fist0
Rubyprogramming~10 mins

File.readlines for line-by-line in Ruby - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - File.readlines for line-by-line
Open file
↓
Read all lines into array
↓
Iterate over array
↓
Process each line
↓
Close file
The program opens a file, reads all lines into an array, then processes each line one by one.
Execution Sample
Ruby
lines = File.readlines('example.txt')
lines.each do |line|
  puts line.chomp
end
Reads all lines from 'example.txt' into an array and prints each line without extra newline.
Execution Table
StepActionEvaluationResult
1Call File.readlines('example.txt')Reads entire fileArray of lines: ["Hello\n", "World\n", "Ruby\n"]
2Start iteration over arrayFirst element: "Hello\n"line = "Hello\n"
3Print line.chompRemove trailing newlineOutput: Hello
4Next iterationSecond element: "World\n"line = "World\n"
5Print line.chompRemove trailing newlineOutput: World
6Next iterationThird element: "Ruby\n"line = "Ruby\n"
7Print line.chompRemove trailing newlineOutput: Ruby
8End iterationNo more elementsIteration stops
💡 All lines processed, iteration ends
Variable Tracker
VariableStartAfter 1After 2After 3Final
linesnil["Hello\n", "World\n", "Ruby\n"]["Hello\n", "World\n", "Ruby\n"]["Hello\n", "World\n", "Ruby\n"]["Hello\n", "World\n", "Ruby\n"]
linenil"Hello\n""World\n""Ruby\n"nil
Key Moments - 3 Insights
Why does each line include a newline character at first?
File.readlines reads each line including the newline character '\n', as shown in execution_table step 1 where lines contain '\n'.
Why do we use line.chomp when printing?
line.chomp removes the trailing newline '\n' so the output lines don't have extra blank lines, as seen in steps 3, 5, and 7.
Does File.readlines keep the file open during iteration?
No, File.readlines reads all lines at once and closes the file immediately, so iteration works on the array in memory (step 1).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'line' at step 4?
A"Hello\n"
B"World\n"
C"Ruby\n"
Dnil
💡 Hint
Check the 'Action' and 'Evaluation' columns at step 4 in execution_table.
At which step does the iteration stop because there are no more lines?
AStep 6
BStep 7
CStep 8
DStep 3
💡 Hint
Look for the step with 'End iteration' and 'No more elements' in execution_table.
If the file had 5 lines instead of 3, how would the variable 'lines' change in variable_tracker?
AIt would have 5 elements in the array instead of 3
BIt would still have 3 elements
CIt would be nil
DIt would be a string, not an array
💡 Hint
Variable 'lines' holds all lines read; more lines means a longer array (see variable_tracker).
Concept Snapshot
File.readlines('filename') reads all lines into an array.
Each element includes the newline character '\n'.
Use .each to loop line-by-line.
Use line.chomp to remove trailing newline when printing.
File is closed after reading all lines.
Full Transcript
This example shows how Ruby's File.readlines method reads all lines from a file into an array. Each line includes a newline character at the end. We then loop over this array using each, processing one line at a time. Using line.chomp removes the newline for clean output. The file is opened and closed automatically during the read. The variable 'lines' holds the array of all lines, and 'line' holds the current line during iteration. The iteration stops when all lines are processed.

Practice

(1/5)
1. What does File.readlines('example.txt') return in Ruby?
easy
A. A hash with line numbers as keys and lines as values
B. A string containing the entire file content
C. An array where each element is a line from the file, including newline characters
D. An integer representing the number of lines in the file

Solution

  1. Step 1: Understand File.readlines behavior

    File.readlines reads the whole file and returns an array of lines.
  2. Step 2: Check line content format

    Each line includes the newline character at the end unless removed by chomp.
  3. Final Answer:

    An array where each element is a line from the file, including newline characters -> Option C
  4. Quick Check:

    File.readlines returns array of lines [OK]
Hint: Remember: File.readlines returns an array of lines with newlines [OK]
Common Mistakes:
  • Thinking it returns a single string
  • Assuming it returns a hash or dictionary
  • Believing it returns just the line count
2. Which of the following is the correct syntax to read all lines from a file named data.txt into an array in Ruby?
easy
A. File.read_lines[]('data.txt')
B. File.read('data.txt')
C. File.read_lines('data.txt')
D. File.readlines('data.txt')

Solution

  1. Step 1: Recall correct method name

    The correct Ruby method to read lines is File.readlines (no underscore or plural misspelling).
  2. Step 2: Check method call syntax

    The method is called with parentheses and the filename as a string argument.
  3. Final Answer:

    File.readlines('data.txt') -> Option D
  4. Quick Check:

    Correct method name and syntax = File.readlines('data.txt') [OK]
Hint: Use exact method name: File.readlines('filename') [OK]
Common Mistakes:
  • Using underscores instead of camel case
  • Misspelling the method name
  • Omitting parentheses or using wrong brackets
3. Given a file 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]
medium
A. Line 2
B. Line 1
C. Line 3
D. nil

Solution

  1. Step 1: Understand File.readlines output

    The file lines are read into an array: ["Line 1\n", "Line 2\n", "Line 3\n"].
  2. Step 2: Access the second element

    Array indexing starts at 0, so lines[1] is "Line 2\n".
  3. Final Answer:

    Line 2 -> Option A
  4. Quick Check:

    Index 1 = second line = Line 2 [OK]
Hint: Remember arrays start at 0; lines[1] is second line [OK]
Common Mistakes:
  • Assuming indexing starts at 1
  • Forgetting newline characters affect output
  • Expecting nil for valid index
4. What is wrong with this Ruby code snippet?
lines = File.readlines('file.txt')
lines.each do |line|
  puts line.chomp
end

Assuming file.txt exists and is readable.
medium
A. It will skip the first line of the file
B. Nothing is wrong; it correctly prints each line without newlines
C. It will print lines with extra newlines
D. It will raise an error because chomp is not a method

Solution

  1. Step 1: Analyze File.readlines usage

    File.readlines reads all lines into an array, each ending with a newline.
  2. Step 2: Check iteration and chomp usage

    Using each to iterate and chomp removes trailing newline before printing.
  3. Final Answer:

    Nothing is wrong; it correctly prints each line without newlines -> Option B
  4. Quick Check:

    chomp removes newline, so output is clean [OK]
Hint: Use chomp to remove newlines when printing lines [OK]
Common Mistakes:
  • Thinking chomp is invalid method
  • Expecting extra newlines despite chomp
  • Assuming lines are skipped
5. You want to read a file 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?
hard
A. File.readlines('data.txt').select { |line| line.downcase.include?('error') }
B. File.readlines('data.txt').map { |line| line.include?('error') }
C. File.readlines('data.txt').filter { |line| line.include?('Error') }
D. File.readlines('data.txt').reject { |line| line.downcase.include?('error') }

Solution

  1. Step 1: Use File.readlines to get all lines

    This returns an array of lines from the file.
  2. Step 2: Filter lines case-insensitively

    Use select to keep lines where line.downcase.include?('error') is true.
  3. Step 3: Check other options

    File.readlines('data.txt').map { |line| line.include?('error') } uses map which 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.
  4. Final Answer:

    File.readlines('data.txt').select { |line| line.downcase.include?('error') } -> Option A
  5. Quick Check:

    select + downcase + include? = correct filter [OK]
Hint: Use select with downcase and include? for case-insensitive filtering [OK]
Common Mistakes:
  • Using map instead of select
  • Ignoring case sensitivity
  • Using reject instead of select
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard