Ruby - File IOYou 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']) }Check Answer
Step-by-Step SolutionSolution:Step 1: Choose correct file mode for writing'w' mode overwrites or creates file for writing.Step 2: Write each name on separate lineUsing each with f.puts writes each name with newline.Final Answer:File.open('names.txt', 'w') { |f| ['Alice', 'Bob'].each { |name| f.puts name } } -> Option BQuick 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 writeTrying to read with write methods
Master "File IO" in Ruby9 interactive learning modes - each teaches the same concept differentlyLearnWhyDeepVisualTryChallengeProjectRecallTime
More Ruby Quizzes Blocks, Procs, and Lambdas - Proc vs lambda differences (arity, return) - Quiz 6medium Class Methods and Variables - Constants in classes - Quiz 15hard Classes and Objects - Why everything is an object in Ruby - Quiz 7medium Enumerable and Collection Processing - Find/detect for first match - Quiz 13medium Enumerable and Collection Processing - Any?, all?, none? predicates - Quiz 12easy File IO - File.open with block (auto-close) - Quiz 4medium Inheritance - Why single inheritance in Ruby - Quiz 5medium Inheritance - Subclass with < operator - Quiz 15hard Modules and Mixins - Namespacing with modules - Quiz 8hard Modules and Mixins - Prepend for method chain insertion - Quiz 3easy