Bird
0
0

Given the array words = ["cat", "dog", "bird", "cow"], which code snippet uses the match operator to find the first word containing the letter 'i' and returns its index in the array?

hard📝 Application Q15 of 15
Ruby - Regular Expressions
Given the array words = ["cat", "dog", "bird", "cow"], which code snippet uses the match operator to find the first word containing the letter 'i' and returns its index in the array?
Awords.find { |w| w =~ /i/ }
Bwords.find_index { |w| w =~ /i/ }
Cwords.index { |w| w.include?('i') }
Dwords.select { |w| w =~ /i/ }
Step-by-Step Solution
Solution:
  1. Step 1: Understand the goal

    We want the index of the first word containing 'i'.
  2. Step 2: Use find_index with match operator

    find_index returns the index of the first element where the block is true. Using w =~ /i/ returns index or nil, so truthy means match found.
  3. Step 3: Check other options

    words.index { |w| w.include?('i') } uses include? which works but is not using the match operator. words.find { |w| w =~ /i/ } returns the word, not index. words.select { |w| w =~ /i/ } returns all matches, not index.
  4. Final Answer:

    words.find_index { |w| w =~ /i/ } -> Option B
  5. Quick Check:

    find_index with =~ returns correct index [OK]
Quick Trick: Use find_index with =~ to get index of first match [OK]
Common Mistakes:
  • Using find instead of find_index for index
  • Using include? instead of =~
  • Expecting select to return single index

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes