Bird
0
0

Identify the error in this Ruby code snippet:

medium📝 Debug Q14 of 15
Ruby - File IO
Identify the error in this Ruby code snippet:
file = File.open('log.txt', 'w') do |f|
  f.puts 'Log entry'
end
file.puts 'Another entry'
Afile is nil because File.open with block returns the block's value, not the file object.
BThe file is not opened in write mode.
CMissing block parameter |f| in File.open.
DFile is not closed automatically.
Step-by-Step Solution
Solution:
  1. Step 1: Understand return value of File.open with block

    When using a block, File.open returns the block's last expression, not the file object.
  2. Step 2: Analyze variable 'file'

    Here, 'file' is assigned the block's return value, which is nil because f.puts returns nil. So calling file.puts causes an error.
  3. Final Answer:

    file is nil because File.open with block returns the block's value, not the file object. -> Option A
  4. Quick Check:

    File.open block returns block value, not file [OK]
Quick Trick: File.open with block returns block result, not file object [OK]
Common Mistakes:
  • Expecting File.open with block to return file object
  • Trying to use file after block ends
  • Ignoring file mode argument

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes