Bird
0
0

You want to add a timestamp line to a log file without deleting existing logs. Which Ruby code correctly does this?

hard📝 Application Q8 of 15
Ruby - File IO
You want to add a timestamp line to a log file without deleting existing logs. Which Ruby code correctly does this?
AFile.open('log.txt', 'w') { |f| f.puts Time.now }
BFile.open('log.txt', 'r+') { |f| f.puts Time.now }
CFile.open('log.txt', 'r') { |f| f.puts Time.now }
DFile.open('log.txt', 'a') { |f| f.puts Time.now }
Step-by-Step Solution
Solution:
  1. Step 1: Choose mode that preserves existing content

    'a' mode appends data without deleting existing file content.
  2. Step 2: Check other modes

    'w' overwrites file, 'r' is read-only, 'r+' allows read/write but does not append automatically.
  3. Final Answer:

    File.open('log.txt', 'a') { |f| f.puts Time.now } -> Option D
  4. Quick Check:

    Append mode adds timestamp without deleting logs = B [OK]
Quick Trick: Use 'a' to add without erasing existing file data [OK]
Common Mistakes:
  • Using 'w' and losing old logs
  • Trying to write in 'r' mode
  • Assuming 'r+' appends automatically

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes