Bird
0
0

The following code is intended to create an array of 3 separate empty arrays. What is the problem?

medium📝 Debug Q14 of 15
Ruby - Arrays
The following code is intended to create an array of 3 separate empty arrays. What is the problem?
arr = Array.new(3, [])
arr[0] << 1
puts arr.inspect
A[[1], [1], [1]]
B[[1], [], []]
C[[], [], []]
DSyntaxError
Step-by-Step Solution
Solution:
  1. Step 1: Understand Array.new with default object

    Using Array.new(3, []) creates 3 references to the same empty array, not 3 separate arrays.
  2. Step 2: Analyze mutation effect

    When arr[0] << 1 runs, it adds 1 to the shared array, so all elements show the change.
  3. Final Answer:

    [[1], [1], [1]] -> Option A
  4. Quick Check:

    Same object repeated causes all elements to change [OK]
Quick Trick: Use block with Array.new for separate objects [OK]
Common Mistakes:
MISTAKES
  • Expecting separate arrays but all share one object
  • Not using block form for unique elements
  • Assuming << affects only one element

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes