Ruby - File IOWhich Ruby code snippet correctly opens a file named 'data.txt' for reading?AFile.open('data.txt', 'w') { |file| puts file.read }BFile.open('data.txt', 'r') { |file| puts file.read }CFile.open('data.txt', 'a') { |file| puts file.read }DFile.open('data.txt', 'x') { |file| puts file.read }Check Answer
Step-by-Step SolutionSolution:Step 1: Identify the mode for readingIn Ruby, 'r' mode opens a file for reading.Step 2: Check code correctnessFile.open('data.txt', 'r') { |file| puts file.read } uses 'r' mode and reads the file content correctly.Final Answer:File.open('data.txt', 'r') { |file| puts file.read } -> Option BQuick Check:Read mode is 'r' in Ruby [OK]Quick Trick: Use 'r' mode to open files for reading [OK]Common Mistakes:Using 'w' or 'a' modes when intending to readConfusing 'x' mode which is for exclusive creationNot using a block to handle the file safely
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