0
0
Rubyprogramming~20 mins

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

Choose your learning style9 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.