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 a file with File.read?
Given a file named example.txt containing the text
Hello, Ruby!, what will the following code output?Ruby
content = File.read('example.txt') puts content
Attempts:
2 left
💡 Hint
File.read reads the whole file content as a string.
✗ Incorrect
File.read returns the entire content of the file as a string. Here, it reads 'Hello, Ruby!' and prints it.
🧠 Conceptual
intermediate1:30remaining
What does File.read return if the file is empty?
If you use
File.read('empty.txt') on an empty file, what will be the returned value?Attempts:
2 left
💡 Hint
Think about what reading an empty file means as text.
✗ Incorrect
Reading an empty file returns an empty string, not nil or an error.
🔧 Debug
advanced2:00remaining
Why does this code raise an error?
This code tries to read a file but raises an error. What is the cause?
Ruby
content = File.read()
puts contentAttempts:
2 left
💡 Hint
Check the method signature for File.read.
✗ Incorrect
File.read requires a filename argument. Calling it without arguments raises ArgumentError.
❓ Predict Output
advanced2:00remaining
What is the output when reading a file with encoding specified?
Given a file
utf8.txt containing UTF-8 text, what does this code output?Ruby
content = File.read('utf8.txt', encoding: 'UTF-8') puts content.encoding.name
Attempts:
2 left
💡 Hint
File.read can take encoding option to read file with specific encoding.
✗ Incorrect
Specifying encoding: 'UTF-8' makes File.read return a string with UTF-8 encoding.
🧠 Conceptual
expert2:30remaining
How many bytes does File.read return when reading a binary file?
If you read a binary file with
File.read('image.png', mode: 'rb'), what is the type and length of the returned object?Attempts:
2 left
💡 Hint
File.read returns a string even in binary mode, but bytes are raw data.
✗ Incorrect
File.read returns a String containing all bytes. The length is the file size in bytes. Encoding is ASCII-8BIT in binary mode.