Bird
0
0

You want to save a list of names to a file, one per line, using Ruby. Which code correctly does this?

hard📝 Application Q8 of 15
Ruby - File IO
You want to save a list of names to a file, one per line, using Ruby. Which code correctly does this?
AFile.open('names.txt', 'a') { |f| f.read(['Alice', 'Bob']) }
BFile.open('names.txt', 'w') { |f| ['Alice', 'Bob'].each { |name| f.puts name } }
CFile.open('names.txt', 'r') { |f| ['Alice', 'Bob'].each { |name| f.puts name } }
DFile.open('names.txt', 'w') { |f| f.write(['Alice', 'Bob']) }
Step-by-Step Solution
Solution:
  1. Step 1: Choose correct file mode for writing

    'w' mode overwrites or creates file for writing.
  2. Step 2: Write each name on separate line

    Using each with f.puts writes each name with newline.
  3. Final Answer:

    File.open('names.txt', 'w') { |f| ['Alice', 'Bob'].each { |name| f.puts name } } -> Option B
  4. Quick Check:

    Write list line-by-line using 'w' and puts [OK]
Quick Trick: Use 'w' mode and puts inside each loop to write lines [OK]
Common Mistakes:
  • Using 'r' mode to write
  • Trying to read with write methods

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes