Bird
0
0

How can you combine flat_map with a condition to extract only even numbers from the sub-arrays?

hard📝 Application Q9 of 15
Ruby - Enumerable and Collection Processing
How can you combine flat_map with a condition to extract only even numbers from the sub-arrays?
arr = [[1, 2], [3, 4], [5, 6]]
Aarr.flat_map { |sub| sub.flatten if sub.include?(2) }
Barr.flat_map { |sub| sub.all?(&:even?) ? sub : [] }
Carr.flat_map { |sub| sub if sub.any?(&:even?) }
Darr.flat_map { |sub| sub.select(&:even?) }
Step-by-Step Solution
Solution:
  1. Step 1: Understand the requirement

    We want to extract only the even numbers from each sub-array.
  2. Step 2: Use select inside flat_map

    Using select(&:even?) filters even numbers, flat_map flattens them into one array.
  3. Final Answer:

    arr.flat_map { |sub| sub.select(&:even?) } -> Option D
  4. Quick Check:

    flat_map + select filters and flattens even numbers [OK]
Quick Trick: Use select inside flat_map to filter elements [OK]
Common Mistakes:
  • Using all? which filters entire sub-array
  • Returning nil or empty arrays incorrectly
  • Misusing flatten inside block

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes