flat_map expects the block to return arrays or enumerables to flatten one level; returning integers causes flattening to fail or unexpected results.
Final Answer:
flat_map block returns integers, not arrays, so flattening fails. -> Option D
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
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.
Step 2: Use flat_map to flatten the mapped arrays
flat_map will flatten the arrays of uppercase words into a single flat array.
Final Answer:
group.map { |w| w.upcase } -> Option A
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 unknownstrongwhile earning +1 Grip toward your certificate.