Bird
0
0

Which Ruby code snippet correctly opens a file named 'data.txt' for reading?

easy📝 Syntax Q3 of 15
Ruby - File IO
Which 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 }
Step-by-Step Solution
Solution:
  1. Step 1: Identify the mode for reading

    In Ruby, 'r' mode opens a file for reading.
  2. Step 2: Check code correctness

    File.open('data.txt', 'r') { |file| puts file.read } uses 'r' mode and reads the file content correctly.
  3. Final Answer:

    File.open('data.txt', 'r') { |file| puts file.read } -> Option B
  4. Quick 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 read
  • Confusing 'x' mode which is for exclusive creation
  • Not using a block to handle the file safely

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes