0
0
Rubyprogramming~20 mins

File.read for entire content 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 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
AHello, Ruby!
BFile.read
Cnil
DAn error because File.read needs a block
Attempts:
2 left
💡 Hint
File.read reads the whole file content as a string.
🧠 Conceptual
intermediate
1: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?
AAn empty string ""
Bnil
C0
DRaises an error
Attempts:
2 left
💡 Hint
Think about what reading an empty file means as text.
🔧 Debug
advanced
2: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 content
AFile.read returns nil and puts fails
BMissing filename argument causes ArgumentError
CFile.read needs a block, so error is raised
DFile.read cannot read text files
Attempts:
2 left
💡 Hint
Check the method signature for File.read.
Predict Output
advanced
2: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
AUTF-16
BASCII-8BIT
CUTF-8
DEncodingError
Attempts:
2 left
💡 Hint
File.read can take encoding option to read file with specific encoding.
🧠 Conceptual
expert
2: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?
AA File object opened in binary mode
BAn Array of bytes, length equals file size in bytes
CA String with UTF-8 encoding, length equals number of characters
DA String containing all bytes of the file, length equals file size in bytes
Attempts:
2 left
💡 Hint
File.read returns a string even in binary mode, but bytes are raw data.