Bird
0
0

Identify the error in this Ruby code snippet:

medium📝 Debug Q14 of 15
Ruby - Enumerable and Collection Processing
Identify the error in this Ruby code snippet:
arr = [1, 2, 3, 4]
result = arr.flat_map { |x| x * 2 }
puts result.inspect
Aflat_map cannot be called on nested arrays.
BThe variable 'result' is not assigned properly.
CThe syntax of the block is incorrect.
Dflat_map block returns integers, not arrays, so flattening fails.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze block return values

    The block { |x| x * 2 } returns integers, not arrays or enumerables.
  2. Step 2: Understand flat_map flattening requirement

    flat_map expects the block to return arrays or enumerables to flatten one level; returning integers causes flattening to fail or unexpected results.
  3. Final Answer:

    flat_map block returns integers, not arrays, so flattening fails. -> Option D
  4. Quick Check:

    Block must return arrays for flat_map flattening [OK]
Quick Trick: Block must return arrays, not single values, for flat_map [OK]
Common Mistakes:
  • Returning single values instead of arrays in block
  • Assuming flat_map works like map without flattening
  • Misunderstanding flat_map usage on nested arrays

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes