Bird
0
0

This Ruby code tries to open a file for reading and writing:

medium📝 Debug Q6 of 15
Ruby - File IO
This Ruby code tries to open a file for reading and writing:
File.open('data.txt', 'r') do |f|
  f.puts 'New line'
end

What is the problem here?
AFile opened in 'r' mode truncates file
BFile opened in 'r' mode cannot write, causes error
CFile opened in 'r' mode appends data
DNo problem, code works fine
Step-by-Step Solution
Solution:
  1. Step 1: Check 'r' mode capabilities

    'r' mode opens file for reading only, no writing allowed.
  2. Step 2: Writing with 'puts' causes error

    Calling 'puts' on file opened in 'r' mode raises an IOError because writing is not permitted.
  3. Final Answer:

    File opened in 'r' mode cannot write, causes error -> Option B
  4. Quick Check:

    'r' mode is read-only, writing causes error = B [OK]
Quick Trick: 'r' mode forbids writing, use 'r+' for read/write [OK]
Common Mistakes:
  • Assuming 'r' allows writing
  • Confusing 'r' with 'r+' mode
  • Ignoring runtime error on write

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes