Bird
0
0

Which of the following is the correct syntax to open a file named data.txt for reading using a block in Ruby?

easy📝 Syntax Q12 of 15
Ruby - File IO
Which of the following is the correct syntax to open a file named data.txt for reading using a block in Ruby?
AFile.open('data.txt') |file| puts file.read end
BFile.open('data.txt') puts file.read end
CFile.open('data.txt') { |file| puts file.read }
DFile.open('data.txt') do puts file.read end
Step-by-Step Solution
Solution:
  1. Step 1: Identify correct block syntax

    Ruby uses either curly braces or do...end with a block parameter like |file|.
  2. Step 2: Check each option

    File.open('data.txt') { |file| puts file.read } correctly uses { |file| ... }. Others have syntax errors or missing block parameters.
  3. Final Answer:

    File.open('data.txt') { |file| puts file.read } -> Option C
  4. Quick Check:

    Correct block syntax = File.open('data.txt') { |file| puts file.read } [OK]
Quick Trick: Use {|var| ...} or do |var| ... end for blocks [OK]
Common Mistakes:
  • Missing block parameter |file|
  • Incorrect block delimiters
  • Omitting do or braces

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes