Challenge - 5 Problems
Ruby IO Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Ruby code using mode 'r'?
Consider this Ruby code that tries to read a file in 'r' mode. What will it output if the file 'example.txt' contains the text 'Hello World'?
Ruby
File.open('example.txt', 'r') do |file| puts file.read end
Attempts:
2 left
💡 Hint
Mode 'r' opens the file for reading only.
✗ Incorrect
The 'r' mode opens the file for reading. Since the file exists and contains 'Hello World', the program prints that text.
❓ Predict Output
intermediate2:00remaining
What happens when opening a file with mode 'w'?
Given this Ruby code, what will be the content of 'output.txt' after running it?
Ruby
File.open('output.txt', 'w') do |file| file.write('First line') end File.open('output.txt', 'w') do |file| file.write('Second line') end
Attempts:
2 left
💡 Hint
Mode 'w' overwrites the file each time it opens it.
✗ Incorrect
Each time the file is opened with 'w', it clears the previous content. So after the second write, only 'Second line' remains.
❓ Predict Output
advanced2:00remaining
What is the output after appending text with mode 'a'?
Assuming 'log.txt' initially contains 'Start\n', what will be the content after running this Ruby code?
Ruby
File.open('log.txt', 'a') do |file| file.puts('Entry 1') end File.open('log.txt', 'a') do |file| file.puts('Entry 2') end content = File.read('log.txt') puts content
Attempts:
2 left
💡 Hint
Mode 'a' adds new content to the end without deleting existing content.
✗ Incorrect
The 'a' mode appends text. So the original 'Start\n' stays, and 'Entry 1' and 'Entry 2' are added on new lines.
❓ Predict Output
advanced2:00remaining
What error occurs when opening a non-existent file in 'r' mode?
What happens when this Ruby code runs and 'missing.txt' does not exist?
Ruby
File.open('missing.txt', 'r') do |file| puts file.read end
Attempts:
2 left
💡 Hint
Mode 'r' requires the file to exist.
✗ Incorrect
Opening a non-existent file in 'r' mode raises an error because the file must exist to read it.
🧠 Conceptual
expert2:00remaining
How do 'w' and 'a' modes differ when writing to a file?
Which statement correctly describes the difference between opening a file in 'w' mode versus 'a' mode in Ruby?
Attempts:
2 left
💡 Hint
Think about what happens to existing content in each mode.
✗ Incorrect
'w' mode clears the file before writing, while 'a' mode adds new content at the end preserving existing data.