Bird
0
0

Given the array animals = ["lion", "tiger", "bear", "leopard"], which code snippet uses the match operator to find all animals containing the substring ea?

hard📝 Application Q8 of 15
Ruby - Regular Expressions
Given the array animals = ["lion", "tiger", "bear", "leopard"], which code snippet uses the match operator to find all animals containing the substring ea?
Aanimals.find { |a| a =~ /ea/ }
Banimals.select { |a| a =~ /ea/ }
Canimals.map { |a| a =~ /ea/ }
Danimals.reject { |a| a =~ /ea/ }
Step-by-Step Solution
Solution:
  1. Step 1: Understand the goal

    We want all elements containing "ea".
  2. Step 2: Use select with =~

    Select returns all elements where the block is truthy; =~ returns index or nil, so non-nil is truthy.
  3. Step 3: Analyze options

    animals.select { |a| a =~ /ea/ } correctly selects all matching elements. animals.find { |a| a =~ /ea/ } returns only the first match. animals.map { |a| a =~ /ea/ } returns indices or nils, not filtered elements. animals.reject { |a| a =~ /ea/ } rejects matches.
  4. Final Answer:

    animals.select { |a| a =~ /ea/ } -> Option B
  5. Quick Check:

    select filters all matching elements [OK]
Quick Trick: Use select with =~ to filter all matching strings [OK]
Common Mistakes:
  • Using find instead of select to get all matches
  • Using map which returns indices, not filtered elements
  • Using reject which excludes matches

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes