Bird
0
0

What will be the output of this Ruby code if file.txt initially contains "Line1\n"?

medium📝 Predict Output Q4 of 15
Ruby - File IO
What will be the output of this Ruby code if file.txt initially contains "Line1\n"?
File.open('file.txt', 'a') do |f|
  f.puts 'Line2'
end
content = File.read('file.txt')
puts content
ALine2\n
BLine1\nLine2\n
CLine1\n
DError because file is opened in append mode
Step-by-Step Solution
Solution:
  1. Step 1: Understand append mode effect

    Opening with 'a' adds new content at the end without deleting existing data.
  2. Step 2: Analyze code output

    After appending 'Line2', reading the file shows original 'Line1' plus new 'Line2' on separate lines.
  3. Final Answer:

    Line1\nLine2\n -> Option B
  4. Quick Check:

    Append mode adds lines, output includes both lines = A [OK]
Quick Trick: Append mode keeps old content, adds new at end [OK]
Common Mistakes:
  • Assuming append mode erases old content
  • Expecting error when appending
  • Confusing output with only new line

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes