Bird
0
0

You want to create a Ruby script that reads a file notes.txt, appends the line "New note added", and then reads the updated content to print it. Which sequence of file modes should you use?

hard📝 Application Q15 of 15
Ruby - File IO
You want to create a Ruby script that reads a file notes.txt, appends the line "New note added", and then reads the updated content to print it. Which sequence of file modes should you use?
AOpen with 'r' to read, then 'a' to append, then 'r' to read again.
BOpen with 'a' to append, then 'r' to read the updated content.
COpen with 'w' to write, then 'a' to append, then 'r' to read.
DOpen with 'r' to read, then 'w' to write, then 'r' to read again.
Step-by-Step Solution
Solution:
  1. Step 1: Read the original file

    Use 'r' mode to read the existing content without changing it.
  2. Step 2: Append the new line

    Use 'a' mode to add "New note added" at the end without erasing.
  3. Step 3: Read the updated content

    Open again with 'r' mode to read and print the updated file content.
  4. Final Answer:

    Open with 'r' to read, then 'a' to append, then 'r' to read again. -> Option A
  5. Quick Check:

    Read, append, read = 'r', 'a', 'r' [OK]
Quick Trick: Read first, append with 'a', then read again [OK]
Common Mistakes:
  • Using 'w' which erases content before appending
  • Trying to append before reading original content
  • Not reopening file to read updated content

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes