Bird
0
0

What is the output of the following Ruby code?

medium📝 Predict Output Q13 of 15
Ruby - Enumerable and Collection Processing
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
A[2, 4, 6, 8]
B[[2, 4], [6, 8]]
C[1, 2, 3, 4]
D[[1, 2], [3, 4]]
Step-by-Step Solution
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]
Quick Trick: 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes