It writes "Line 1\n" to "data.txt", creating or overwriting the file.
Step 2: Analyze second File.write call
It overwrites the entire file content with "Line 2\n" because File.write overwrites by default.
Final Answer:
Line 2\n -> Option A
Quick Check:
File.write overwrites, so last write stays = B [OK]
Hint: Each File.write overwrites unless mode 'a' is set [OK]
Common Mistakes:
Assuming File.write appends by default
Expecting both lines to be in the file
Confusing newline characters with extra lines
4. The following Ruby code is intended to append "More text" to the file "notes.txt". What is the error?
File.write("notes.txt", "More text")
medium
A. The filename should be a symbol, not a string.
B. File.write overwrites instead of appending; mode 'a' is missing.
C. The string "More text" must be inside single quotes.
D. File.write cannot write strings, only bytes.
Solution
Step 1: Understand File.write default mode
By default, File.write overwrites the file content.
Step 2: Identify how to append
To append, you must specify mode: File.write("notes.txt", "More text", mode: "a").
Final Answer:
File.write overwrites instead of appending; mode 'a' is missing. -> Option B
Quick Check:
Append needs mode 'a' = A [OK]
Hint: Use mode: 'a' to append with File.write [OK]
Common Mistakes:
Not specifying mode to append
Using symbols instead of strings for filename
Thinking quotes style affects writing
Believing File.write can't write strings
5. You want to write multiple lines to a file "log.txt" without overwriting existing content. Which Ruby code correctly appends these lines using File.write?
hard
A. File.write("log.txt", "First line\nSecond line\n", append: true)
B. File.write("log.txt", "First line\nSecond line\n")
C. File.write("log.txt", "First line\nSecond line\n", mode: "w")
D. File.write("log.txt", "First line\nSecond line\n", mode: "a")
Solution
Step 1: Identify how to append with File.write
Appending requires mode set to "a" (append mode).
Step 2: Check options for correct syntax
File.write("log.txt", "First line\nSecond line\n", mode: "a") uses mode: "a" correctly to append multiple lines.
Final Answer:
File.write("log.txt", "First line\nSecond line\n", mode: "a") -> Option D
Quick Check:
Append mode is 'a' in File.write = D [OK]
Hint: Use mode: 'a' to append multiple lines safely [OK]
Common Mistakes:
Omitting mode for append
Using mode 'w' which overwrites
Using invalid option 'append: true'
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.