0
0
Rubyprogramming~20 mins

Flat_map for nested flattening in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Flat_map Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of flat_map with nested arrays
What is the output of this Ruby code using flat_map to flatten nested arrays?
Ruby
nested = [[1, 2], [3, 4], [5]]
result = nested.flat_map { |arr| arr }
puts result.inspect
A[1, 2, 3, 4, 5]
B[1, 2, [3, 4], 5]
C[[1], [2], [3], [4], [5]]
D[[1, 2], [3, 4], [5]]
Attempts:
2 left
💡 Hint
Remember that flat_map maps and then flattens one level.
Predict Output
intermediate
2:00remaining
Using flat_map with transformation
What is the output of this Ruby code that uses flat_map to transform and flatten nested arrays?
Ruby
nested = [[1, 2], [3, 4], [5]]
result = nested.flat_map { |arr| arr.map { |x| x * 2 } }
puts result.inspect
A[2, 4, 6, 8, 10]
B[[2, 4], [6, 8], [10]]
C[1, 2, 3, 4, 5]
D[[1, 4], [9, 16], [25]]
Attempts:
2 left
💡 Hint
The block doubles each number, then flat_map flattens the result.
🔧 Debug
advanced
2:00remaining
Result of incorrect flat_map usage with each
What is the output of this Ruby code when using flat_map incorrectly?
Ruby
nested = [[1, 2], [3, 4], [5]]
result = nested.flat_map do |arr|
  arr.each do |x|
    x * 2
  end
end
puts result.inspect
ASyntaxError: unexpected end-of-input
BNoMethodError: undefined method `flat_map' for Array
C[1, 2, 3, 4, 5]
DTypeError: no implicit conversion of nil into Array
Attempts:
2 left
💡 Hint
Check what the block returns for each element when using flat_map.
🧠 Conceptual
advanced
2:00remaining
Difference between map and flat_map
Which statement best describes the difference between map and flat_map in Ruby?
A<code>map</code> flattens arrays; <code>flat_map</code> only transforms elements without flattening.
B<code>map</code> transforms elements and returns an array of arrays; <code>flat_map</code> transforms and flattens one level.
C<code>map</code> and <code>flat_map</code> are identical in behavior.
D<code>flat_map</code> only works on flat arrays; <code>map</code> works on nested arrays.
Attempts:
2 left
💡 Hint
Think about what happens after the transformation in each method.
Predict Output
expert
3:00remaining
Complex nested flattening with flat_map
What is the output of this Ruby code that uses flat_map twice to flatten a deeply nested array?
Ruby
nested = [[[1, 2], [3]], [[4, 5]], [6]]
result = nested.flat_map { |arr| arr.flat_map { |x| x } }
puts result.inspect
A[1, 2, 3, [4, 5], 6]
B[[1, 2], [3], [4, 5], 6]
C[[1, 2, 3], [4, 5, 6]]
D[1, 2, 3, 4, 5, 6]
Attempts:
2 left
💡 Hint
Each flat_map flattens one level after mapping.