You want to read a file and count how many lines contain the word 'error'. Which Ruby code correctly does this using file handling?
hard📝 Application Q15 of 15
Ruby - File IO
You want to read a file and count how many lines contain the word 'error'. Which Ruby code correctly does this using file handling?
Acount = 0
file = File.open('log.txt', 'w')
file.each_line do |line|
count += 1 if line.include?('error')
end
file.close
puts count
Bcount = 0
File.open('log.txt', 'r') do |file|
file.each_line do |line|
count += 1 if line.include?('error')
end
end
puts count
Ccount = 0
File.read('log.txt').each do |line|
count += 1 if line.include?('error')
end
puts count
Dcount = 0
File.open('log.txt') do |file|
file.read.each do |line|
count += 1 if line.include?('error')
end
end
puts count
Step-by-Step Solution
Solution:
Step 1: Identify correct file mode and iteration
count = 0
File.open('log.txt', 'r') do |file|
file.each_line do |line|
count += 1 if line.include?('error')
end
end
puts count opens file in 'r' mode and uses each_line with block, counting lines with 'error'.
Step 2: Check other options for errors
count = 0
file = File.open('log.txt', 'w')
file.each_line do |line|
count += 1 if line.include?('error')
end
file.close
puts count opens file in 'w' (write) mode, wrong for reading; count = 0
File.read('log.txt').each do |line|
count += 1 if line.include?('error')
end
puts count uses File.read but does not handle string properly; count = 0
File.open('log.txt') do |file|
file.read.each do |line|
count += 1 if line.include?('error')
end
end
puts count misses mode argument in File.open.
Final Answer:
count = 0
File.open('log.txt', 'r') do |file|
file.each_line do |line|
count += 1 if line.include?('error')
end
end
puts count -> Option B
Quick Check:
Open file read + each_line + count lines with 'error' [OK]
Quick Trick:Open file in 'r' mode and use each_line to count matches [OK]
Common Mistakes:
Opening file in write mode when reading
Not specifying mode in File.open
Using File.read without splitting lines
Master "File IO" in Ruby
9 interactive learning modes - each teaches the same concept differently