Ruby - File IOYou 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 }Check Answer
Step-by-Step SolutionSolution:Step 1: Choose mode that preserves existing content'a' mode appends data without deleting existing file content.Step 2: Check other modes'w' overwrites file, 'r' is read-only, 'r+' allows read/write but does not append automatically.Final Answer:File.open('log.txt', 'a') { |f| f.puts Time.now } -> Option DQuick 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 logsTrying to write in 'r' modeAssuming 'r+' appends automatically
Master "File IO" in Ruby9 interactive learning modes - each teaches the same concept differentlyLearnWhyDeepVisualTryChallengeProjectRecallTime
More Ruby Quizzes Blocks, Procs, and Lambdas - Method objects with method() - Quiz 4medium Blocks, Procs, and Lambdas - Closures and variable binding - Quiz 14medium Blocks, Procs, and Lambdas - Block given? check - Quiz 14medium Class Methods and Variables - Open classes (reopening classes) - Quiz 15hard Classes and Objects - Initialize method as constructor - Quiz 4medium Enumerable and Collection Processing - Group_by for categorization - Quiz 13medium Error Handling - Ensure for cleanup - Quiz 3easy Error Handling - Why error handling uses rescue - Quiz 1easy Error Handling - Rescue modifier (inline form) - Quiz 3easy File IO - Why file handling matters - Quiz 13medium