Bird
0
0

What is the output of the following Ruby code?

medium📝 Predict Output Q13 of 15
Ruby - Arrays
What is the output of the following Ruby code?
arr = [1, [2, 3], [4, [5]]]
puts arr.flatten.length
A5
B3
C6
D7
Step-by-Step Solution
Solution:
  1. Step 1: Apply flatten to the array

    The nested array [1, [2, 3], [4, [5]]] becomes [1, 2, 3, 4, 5] after flattening.
  2. Step 2: Calculate the length of the flattened array

    The flattened array has 5 elements, so length returns 5.
  3. Final Answer:

    5 -> Option A
  4. Quick Check:

    Flattened array length = 5 [OK]
Quick Trick: Flatten first, then count elements with length [OK]
Common Mistakes:
MISTAKES
  • Counting nested arrays as single elements
  • Forgetting flatten changes nested arrays
  • Miscounting elements after flatten

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes