0
0
Rubyprogramming~5 mins

Flat_map for nested flattening in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the flat_map method do in Ruby?
It applies a block to each element of a collection and then flattens the result by one level, combining mapping and flattening in one step.
Click to reveal answer
intermediate
How is flat_map different from map followed by flatten?
flat_map combines both operations efficiently in one method call, avoiding the creation of intermediate arrays.
Click to reveal answer
beginner
Given arr = [[1, 2], [3, 4]], what is the result of arr.flat_map { |x| x }?
The result is [1, 2, 3, 4] because flat_map flattens one level after mapping.
Click to reveal answer
beginner
Why is flat_map useful for nested arrays?
It lets you transform each nested element and flatten the result in one step, making code simpler and more readable.
Click to reveal answer
beginner
Write a simple Ruby code snippet using flat_map to get all characters from an array of words.
Example:<br>
words = ["cat", "dog"]
chars = words.flat_map { |word| word.chars }
# chars is ["c", "a", "t", "d", "o", "g"]
Click to reveal answer
What does flat_map do after applying the block to each element?
AFlattens the result by one level
BSorts the result
CRemoves duplicates
DReverses the result
Which of these is equivalent to arr.flat_map { |x| x } for a nested array arr?
Aarr.map { |x| x.flatten }
Barr.flatten(2)
Carr.flatten(0)
Darr.map { |x| x }.flatten(1)
What will [1, 2, 3].flat_map { |n| [n, n*2] } return?
A[1, 2, 2, 4, 3, 6]
B[[1, 2], [2, 4], [3, 6]]
C[1, 2, 3, 6]
D[2, 4, 6]
Why might you prefer flat_map over map + flatten?
AIt converts arrays to hashes
BIt is more efficient and concise
CIt removes nil values
DIt sorts the array automatically
What is the output of [[1, 2], [3, 4]].flat_map(&:reverse)?
A[1, 2, 3, 4]
B[[2, 1], [4, 3]]
C[2, 1, 4, 3]
D[[1, 2], [3, 4]]
Explain how flat_map works and why it is useful for nested arrays.
Think about how you transform and then flatten nested lists in one step.
You got /4 concepts.
    Write a Ruby example using flat_map to get all letters from an array of words.
    Use <code>flat_map</code> with <code>word.chars</code> inside the block.
    You got /4 concepts.