Bird
0
0

You want to read the entire content of a file and count how many times the word "ruby" appears, ignoring case. Which code correctly does this?

hard📝 Application Q8 of 15
Ruby - File IO
You want to read the entire content of a file and count how many times the word "ruby" appears, ignoring case. Which code correctly does this?
Atext = File.read('file.txt') puts text.scan(/ruby/i).count
Btext = File.read('file.txt') puts text.scan('ruby').count
Ctext = File.read('file.txt') puts text.count('ruby')
Dtext = File.read('file.txt').downcase puts text.count('ruby')
Step-by-Step Solution
Solution:
  1. Step 1: Read file content

    Use File.read('file.txt') to get full content as string.
  2. Step 2: Count occurrences ignoring case

    Use regex with /ruby/i in scan to find all case-insensitive matches, then count them.
  3. Step 3: Analyze options

    text = File.read('file.txt') puts text.scan(/ruby/i).count uses regex with ignore case flag correctly. text = File.read('file.txt') puts text.scan('ruby').count uses string scan which becomes case-sensitive regex /ruby/, so case-insensitive won't work. Options C and D misuse count which counts characters, not substrings.
  4. Final Answer:

    text = File.read('file.txt') puts text.scan(/ruby/i).count -> Option A
  5. Quick Check:

    Use regex with /i flag and scan to count words = A [OK]
Quick Trick: Use scan(/word/i).count for case-insensitive word count [OK]
Common Mistakes:
  • Using string scan without regex for case-insensitive search
  • Using count method incorrectly on string
  • Calling downcase but scanning plain string

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes