Ruby - File IOWhich Ruby code correctly opens a file for writing using a block?AFile.read('data.txt', 'w') do |file| file.puts 'Hello' endBFile.open('data.txt', 'r') do |file| file.puts 'Hello' endCFile.open('data.txt', 'w') do |file| file.puts 'Hello' endDFile.write('data.txt', 'w') do |file| file.puts 'Hello' endCheck Answer
Step-by-Step SolutionSolution:Step 1: Identify correct method and mode for writingFile.open with mode 'w' opens file for writing; block syntax ensures file closes.Step 2: Check each option's correctnessFile.open('data.txt', 'w') do |file| file.puts 'Hello' end uses File.open with 'w' and block correctly; others misuse methods or modes.Final Answer:File.open('data.txt', 'w') do |file|\n file.puts 'Hello'\nend -> Option CQuick Check:File.open + 'w' + block = correct syntax [OK]Quick Trick: Use File.open with 'w' mode and a block to write safely [OK]Common Mistakes:Using File.read instead of File.open for writingUsing wrong mode like 'r' for writingUsing File.write with a block (not supported)
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