Bird
0
0

Find the problem in this code snippet:

medium📝 Debug Q7 of 15
Ruby - Arrays
Find the problem in this code snippet:
arr = Array.new(3) { [] }
arr[0] << 10
puts arr.inspect
AAll arrays share same object
BNo problem, output is [[10], [], []]
CSyntax error in Array.new block
DOutput is [[], [], []]
Step-by-Step Solution
Solution:
  1. Step 1: Understand block form of Array.new

    Array.new(3) { [] } creates 3 separate empty arrays, one per element.
  2. Step 2: Modify first element

    arr[0] << 10 adds 10 only to first array, others remain empty.
  3. Final Answer:

    No problem, output is [[10], [], []] -> Option B
  4. Quick Check:

    Block form creates unique objects per element [OK]
Quick Trick: Use block to create unique objects in array [OK]
Common Mistakes:
  • Assuming shared arrays
  • Expecting syntax error
  • Confusing with default value form

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes