Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q13 of 15
Ruby - File IO
What will be the output of this Ruby code?
File.open('test.txt', 'w') { |f| f.puts 'Line 1' }
content = File.read('test.txt')
puts content
AError: file not found
Btest.txt
Cnil
DLine 1
Step-by-Step Solution
Solution:
  1. Step 1: Write 'Line 1' to file using block

    The block writes 'Line 1' plus newline to 'test.txt' and closes file.
  2. Step 2: Read file content and print

    File.read reads the file content 'Line 1\n', puts prints it as 'Line 1'.
  3. Final Answer:

    Line 1 -> Option D
  4. Quick Check:

    Write then read file = output written text [OK]
Quick Trick: Write then read file prints what was saved [OK]
Common Mistakes:
  • Expecting filename instead of content
  • Thinking output is nil
  • Assuming file not found error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes