Challenge - 5 Problems
File Read Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of reading lines with File.readlines?
Given a file named
example.txt with these contents:apple banana cherryWhat will this Ruby code output?
lines = File.readlines('example.txt')
puts lines[1]Ruby
lines = File.readlines('example.txt') puts lines[1]
Attempts:
2 left
💡 Hint
Remember that File.readlines keeps the newline characters at the end of each line.
✗ Incorrect
File.readlines reads all lines into an array, each line including its newline character. So lines[1] is 'banana\n'. puts prints this string, resulting in the output 'banana' followed by a newline.
❓ Predict Output
intermediate1: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
Attempts:
2 left
💡 Hint
File.readlines returns an array with one element per line.
✗ Incorrect
File.readlines returns an array where each element is one line from the file. So the size of this array equals the number of lines in the file.
🔧 Debug
advanced2:00remaining
Why does this code raise an error when reading lines?
Consider this Ruby code:
What error will this code raise and why?
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]
Attempts:
2 left
💡 Hint
Check what happens if you try to read a file that is not present.
✗ Incorrect
File.readlines tries to open the file. If the file does not exist, Ruby raises Errno::ENOENT indicating the file was not found.
🧠 Conceptual
advanced2: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?Attempts:
2 left
💡 Hint
Think about memory usage when reading large files.
✗ Incorrect
File.readlines loads all lines into an array at once, which can use a lot of memory for big files. File.foreach reads one line at a time, which is more memory efficient.
❓ Predict Output
expert2:30remaining
What is the output of this code using File.readlines with chomp?
Given a file
fruits.txt with contents:apple banana cherryWhat 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('-')
Attempts:
2 left
💡 Hint
The chomp method removes newline characters from each line.
✗ Incorrect
File.readlines reads lines with newlines. Using map(&:chomp) removes newlines from each line. Joining with '-' produces 'apple-banana-cherry'.