Bird
0
0

How can you read the entire content of a file named config.txt in Ruby without your program crashing if the file does not exist?

hard📝 Application Q9 of 15
Ruby - File IO
How can you read the entire content of a file named config.txt in Ruby without your program crashing if the file does not exist?
AUse <code>content = File.read('config.txt') || ''</code>
BUse <code>begin; content = File.read('config.txt'); rescue Errno::ENOENT; content = nil; end</code>
CUse <code>content = File.readlines('config.txt')</code> and check if empty
DUse <code>File.open('config.txt') { |f| content = f.read }</code> without rescue
Step-by-Step Solution
Solution:
  1. Step 1: Recognize error possibility

    File.read raises an exception if the file is missing.
  2. Step 2: Use exception handling

    Wrap the call in a begin-rescue block to catch Errno::ENOENT and handle missing file gracefully.
  3. Step 3: Analyze other options

    Use content = File.read('config.txt') || '' does not prevent exception; Use content = File.readlines('config.txt') and check if empty reads lines but does not handle missing file; Use File.open('config.txt') { |f| content = f.read } without rescue lacks error handling.
  4. Final Answer:

    Use begin-rescue to catch missing file error -> Option B
  5. Quick Check:

    Rescue Errno::ENOENT to avoid crash [OK]
Quick Trick: Rescue Errno::ENOENT to handle missing files [OK]
Common Mistakes:
  • Assuming File.read returns nil on missing file
  • Using File.readlines without error handling
  • Not rescuing exceptions when reading files

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes