Bird
Raised Fist0
Rubyprogramming~20 mins

File.readlines for line-by-line in Ruby - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
File Read Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of reading lines with File.readlines?
Given a file named example.txt with these contents:
apple
banana
cherry
What will this Ruby code output?
lines = File.readlines('example.txt')
puts lines[1]
Ruby
lines = File.readlines('example.txt')
puts lines[1]
Aananab
Bapple
C
banana
Dcherry
Attempts:
2 left
💡 Hint
Remember that File.readlines keeps the newline characters at the end of each line.
❓ Predict Output
intermediate
1:30remaining
How many lines does File.readlines return?
If a file data.txt contains 5 lines of text, what will File.readlines('data.txt').size return?
Ruby
count = File.readlines('data.txt').size
puts count
A5
B4
C0
D6
Attempts:
2 left
💡 Hint
File.readlines returns an array with one element per line.
🔧 Debug
advanced
2:00remaining
Why does this code raise an error when reading lines?
Consider this Ruby code:
lines = File.readlines('missing.txt')
puts lines[0]

What error will this code raise and why?
Ruby
lines = File.readlines('missing.txt')
puts lines[0]
AErrno::ENOENT (No such file or directory) because the file does not exist
BNoMethodError because lines is nil
CIndexError because lines[0] is out of range
DSyntaxError due to missing quotes
Attempts:
2 left
💡 Hint
Check what happens if you try to read a file that is not present.
🧠 Conceptual
advanced
2:00remaining
What is the difference between File.readlines and File.foreach?
Which statement correctly describes the difference between File.readlines and File.foreach in Ruby?
AFile.readlines writes to a file; File.foreach reads from a file
BFile.readlines reads the entire file into memory as an array; File.foreach reads one line at a time without loading the whole file
CBoth methods read the entire file into memory but return different data types
DFile.readlines reads one line at a time; File.foreach reads the entire file into memory
Attempts:
2 left
💡 Hint
Think about memory usage when reading large files.
❓ Predict Output
expert
2:30remaining
What is the output of this code using File.readlines with chomp?
Given a file fruits.txt with contents:
apple
banana
cherry
What will this code output?
lines = File.readlines('fruits.txt').map(&:chomp)
puts lines.join('-')
Ruby
lines = File.readlines('fruits.txt').map(&:chomp)
puts lines.join('-')
Aapplebanana cherry
Bapple\n-banana\n-cherry\n
Capple banana cherry
Dapple-banana-cherry
Attempts:
2 left
💡 Hint
The chomp method removes newline characters from each line.

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