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?✗ Incorrect
flat_map flattens the mapped result by one level, combining map and flatten.Which of these is equivalent to
arr.flat_map { |x| x } for a nested array arr?✗ Incorrect
flat_map is like map followed by flatten(1).What will
[1, 2, 3].flat_map { |n| [n, n*2] } return?✗ Incorrect
Each number maps to an array of two elements, then flattened one level into a single array.
Why might you prefer
flat_map over map + flatten?✗ Incorrect
flat_map does both operations in one step, improving efficiency and readability.What is the output of
[[1, 2], [3, 4]].flat_map(&:reverse)?✗ Incorrect
Each sub-array is reversed, then flattened one level into a single array.
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.