Bird
0
0

You want to open a file, write data, and always close it even if an error occurs. Which Ruby code correctly uses ensure for this cleanup?

hard📝 Application Q15 of 15
Ruby - Error Handling
You want to open a file, write data, and always close it even if an error occurs. Which Ruby code correctly uses ensure for this cleanup?
Abegin file = File.open('data.txt', 'w') file.write('Hello') rescue file.close end
Bfile = File.open('data.txt', 'w') file.write('Hello') file.close
Cfile = File.open('data.txt', 'w') begin file.write('Hello') ensure file.close end
Dbegin file = File.open('data.txt', 'w') file.write('Hello') ensure file = nil end
Step-by-Step Solution
Solution:
  1. Step 1: Identify correct use of ensure for cleanup

    file = File.open('data.txt', 'w') begin file.write('Hello') ensure file.close end opens the file before begin, writes inside, and closes in ensure, guaranteeing closure.
  2. Step 2: Check other options for errors

    begin file = File.open('data.txt', 'w') file.write('Hello') rescue file.close end closes in rescue, which only runs on errors, not always. file = File.open('data.txt', 'w') file.write('Hello') file.close doesn't handle errors. begin file = File.open('data.txt', 'w') file.write('Hello') ensure file = nil end sets file to nil but doesn't close it.
  3. Final Answer:

    file = File.open('data.txt', 'w') begin file.write('Hello') ensure file.close end -> Option C
  4. Quick Check:

    Ensure always closes file [OK]
Quick Trick: Put cleanup like file.close inside ensure [OK]
Common Mistakes:
  • Closing file only in rescue block
  • Not closing file on error
  • Setting variable to nil instead of closing

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes