Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q4 of 15
Ruby - Enumerable and Collection Processing
What will be the output of this Ruby code?
arr = [[2, 3], [4, 5]]
result = arr.flat_map { |sub| sub.select { |x| x.odd? } }
puts result.inspect
A[3, 5]
B[2, 4]
C[[3], [5]]
D[2, 3, 4, 5]
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the block

    The block uses select to filter odd numbers from each sub-array.
  2. Step 2: Apply flat_map

    flat_map applies the block to each sub-array and then flattens the results by one level.
  3. Step 3: Evaluate each sub-array

    From [2, 3], select odd numbers -> [3]; from [4, 5], select odd numbers -> [5].
  4. Step 4: Flatten one level

    Flattening [[3], [5]] results in [3, 5].
  5. Final Answer:

    [3, 5] -> Option A
  6. Quick Check:

    Filtering odds then flattening one level [OK]
Quick Trick: flat_map flattens after filtering each sub-array [OK]
Common Mistakes:
  • Expecting the output to be nested arrays
  • Confusing odd and even selection
  • Forgetting flat_map flattens one level

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes