Bird
Raised Fist0
Rubyprogramming~10 mins

Flat_map for nested flattening in Ruby - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Flat_map for nested flattening
Start with nested array
↓
Apply flat_map
↓
For each element: map to inner array
↓
Flatten one level
↓
Result: single-level array
flat_map takes each element, maps it to an inner array, then flattens the result by one level to create a single-level array.
Execution Sample
Ruby
nested = [[1, 2], [3, 4], [5]]
flat = nested.flat_map { |arr| arr }
puts flat.inspect
This code flattens one level of nested arrays into a single array using flat_map.
Execution Table
StepCurrent Element (arr)Mapping ResultAccumulated Result
1[1, 2][1, 2][1, 2]
2[3, 4][3, 4][1, 2, 3, 4]
3[5][5][1, 2, 3, 4, 5]
4No more elementsN/A[1, 2, 3, 4, 5]
💡 All nested arrays processed; flat_map returns the flattened array.
Variable Tracker
VariableStartAfter 1After 2After 3Final
nested[[1, 2], [3, 4], [5]][[1, 2], [3, 4], [5]][[1, 2], [3, 4], [5]][[1, 2], [3, 4], [5]][[1, 2], [3, 4], [5]]
flat[][1, 2][1, 2, 3, 4][1, 2, 3, 4, 5][1, 2, 3, 4, 5]
Key Moments - 2 Insights
Why does flat_map flatten only one level instead of all nested levels?
flat_map applies the block to each element and then flattens the result by one level only, as shown in execution_table rows 1-3 where each inner array is added directly without deeper flattening.
What happens if the block returns a non-array element?
If the block returns a non-array, flat_map treats it as a single element and adds it to the result, flattening only one level. This is implied by the mapping result column in the execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the accumulated result after step 2?
A[1, 2, 3, 4]
B[1, 2]
C[3, 4]
D[1, 2, 3]
💡 Hint
Check the 'Accumulated Result' column at step 2 in the execution_table.
At which step does flat_map finish processing all elements?
AStep 3
BStep 4
CStep 2
DStep 1
💡 Hint
Look for the step where 'No more elements' appears in the 'Current Element' column.
If the block returned a single number instead of an array, how would the accumulated result change after step 1?
A[1, 2]
B[[1, 2]]
C[1]
D[[1]]
💡 Hint
Recall flat_map flattens one level; a single number would be added as is, see 'Mapping Result' in execution_table.
Concept Snapshot
flat_map applies a block to each element of a nested array,
then flattens the result by one level.
Syntax: array.flat_map { |element| ... }
Useful to combine map and flatten in one step.
Only flattens one level deep.
Full Transcript
This visual execution shows how Ruby's flat_map works to flatten nested arrays by one level. Starting with a nested array, flat_map applies a block to each inner array element, then combines all results into a single flat array. The execution table tracks each step, showing the current element, the mapping result, and the accumulated result. The variable tracker shows how the 'flat' variable grows after each step. Key moments clarify common confusions about flattening depth and block return types. The quiz tests understanding of the step-by-step process and effects of different block returns.

Practice

(1/5)
1. What does the Ruby method flat_map do when applied to an array of arrays?
easy
A. It removes duplicate elements from the array.
B. It only flattens the array without applying any block.
C. It applies a block to each element and flattens the result by one level.
D. It maps elements but keeps the nested structure intact.

Solution

  1. Step 1: Understand flat_map behavior

    The flat_map method applies a block to each element of the array.
  2. Step 2: Flatten the mapped results

    After mapping, it flattens the resulting array by one level, combining nested arrays into a single array.
  3. Final Answer:

    It applies a block to each element and flattens the result by one level. -> Option C
  4. Quick Check:

    flat_map = map + flatten(1) [OK]
Hint: Remember: flat_map = map + flatten one level [OK]
Common Mistakes:
  • Thinking flat_map flattens all nested levels
  • Confusing flat_map with flatten
  • Assuming flat_map does not apply a block
2. Which of the following is the correct syntax to use flat_map on an array arr to double each number?
easy
A. arr.flat_map do x * 2 end
B. arr.flat_map { |x| [x * 2] }
C. arr.flat_map { x * 2 }
D. arr.flat_map(x) { x * 2 }

Solution

  1. Step 1: Understand flat_map block return

    The block given to flat_map should return an array or enumerable to flatten.
  2. Step 2: Check each option's block return

    arr.flat_map { |x| [x * 2] } returns an array [x * 2], which flat_map will flatten by one level, producing a flat array of doubled values.
  3. Final Answer:

    arr.flat_map { |x| [x * 2] } -> Option B
  4. Quick Check:

    Block must return array for flat_map flattening [OK]
Hint: Return an array inside block for flat_map to flatten [OK]
Common Mistakes:
  • Returning a single value instead of an array in block
  • Using incorrect block syntax
  • Passing arguments incorrectly to flat_map
3. What is the output of the following Ruby code?
arr = [[1, 2], [3, 4]]
result = arr.flat_map { |sub| sub.map { |x| x * 2 } }
puts result.inspect
medium
A. [2, 4, 6, 8]
B. [[2, 4], [6, 8]]
C. [1, 2, 3, 4]
D. [[1, 2], [3, 4]]

Solution

  1. Step 1: Inner map doubles each element

    For each sub-array, sub.map { |x| x * 2 } creates a new array with doubled values: [2,4] and [6,8].
  2. Step 2: flat_map flattens one level

    flat_map combines these arrays into a single flat array: [2, 4, 6, 8].
  3. Final Answer:

    [2, 4, 6, 8] -> Option A
  4. Quick Check:

    flat_map flattens mapped arrays one level [OK]
Hint: flat_map flattens one level after mapping [OK]
Common Mistakes:
  • Expecting nested arrays in output
  • Confusing map with flat_map output
  • Ignoring inner map doubling
4. Identify the error in this Ruby code snippet:
arr = [1, 2, 3, 4]
result = arr.flat_map { |x| x * 2 }
puts result.inspect
medium
A. flat_map cannot be called on nested arrays.
B. The variable 'result' is not assigned properly.
C. The syntax of the block is incorrect.
D. flat_map block returns integers, not arrays, so flattening fails.

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]
Hint: 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
5. Given a nested array of words grouped by their first letter, how can you use flat_map to get a flat array of all words in uppercase?
words = [['apple', 'apricot'], ['banana', 'blueberry'], ['cherry']]
# Fill in the blank:
result = words.flat_map { |group| ________ }
puts result.inspect
hard
A. group.map { |w| w.upcase }
B. group.upcase
C. group.map { w.upcase }
D. group.flat_map { w.upcase }

Solution

  1. Step 1: Map each word to uppercase inside each group

    Use group.map { |w| w.upcase } to convert each word in the sub-array to uppercase.
  2. Step 2: Use flat_map to flatten the mapped arrays

    flat_map will flatten the arrays of uppercase words into a single flat array.
  3. Final Answer:

    group.map { |w| w.upcase } -> Option A
  4. Quick Check:

    flat_map + map for nested uppercase flattening [OK]
Hint: Use map inside flat_map block to transform and flatten [OK]
Common Mistakes:
  • Calling upcase on array instead of strings
  • Using flat_map inside block unnecessarily
  • Returning non-array values from block
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard