Bird
0
0

You want to read a file and count how many lines contain the word 'error'. Which code correctly uses File.open with a block to do this?

hard📝 Application Q8 of 15
Ruby - File IO
You want to read a file and count how many lines contain the word 'error'. Which code correctly uses File.open with a block to do this?
Acount = 0 File.open('log.txt', 'r') do |f| f.each_line { |line| count += 1 if line.include?('error') } end puts count
Bcount = 0 f = File.open('log.txt', 'r') f.each_line { |line| count += 1 if line.include?('error') } f.close puts count
Ccount = 0 File.open('log.txt', 'w') do |f| f.each_line { |line| count += 1 if line.include?('error') } end puts count
Dcount = 0 File.open('log.txt') { |f| f.read.each { |c| count += 1 if c == 'error' } } puts count
Step-by-Step Solution
Solution:
  1. Step 1: Use File.open with block and read mode

    count = 0 File.open('log.txt', 'r') do |f| f.each_line { |line| count += 1 if line.include?('error') } end puts count opens the file in read mode 'r' with a block, which auto-closes the file.
  2. Step 2: Count lines containing 'error'

    Inside the block, it iterates each line and increments count if 'error' is found.
  3. Final Answer:

    count = 0 File.open('log.txt', 'r') do |f| f.each_line { |line| count += 1 if line.include?('error') } end puts count -> Option A
  4. Quick Check:

    File.open with block + read mode + line iteration = A [OK]
Quick Trick: Use File.open with block and 'r' mode to read safely [OK]
Common Mistakes:
  • Using write mode 'w' when reading
  • Not using block to auto-close file
  • Incorrect iteration over characters instead of lines

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes