Bird
0
0

Why does Array.new(3, []) cause unexpected behavior when modifying elements?

hard📝 Conceptual Q10 of 15
Ruby - Arrays
Why does Array.new(3, []) cause unexpected behavior when modifying elements?
ABecause the syntax is invalid
BBecause Array.new cannot create arrays with default values
CBecause all elements reference the same array object
DBecause the array size must be specified as a block
Step-by-Step Solution
Solution:
  1. Step 1: Understand default object behavior

    Array.new(3, []) creates an array where all elements point to the same empty array object.
  2. Step 2: Effect on modification

    Modifying one element modifies all because they share the same object reference.
  3. Final Answer:

    Because all elements reference the same array object -> Option C
  4. Quick Check:

    Default object shared causes unexpected mutations [OK]
Quick Trick: Default objects are shared, use block for unique elements [OK]
Common Mistakes:
  • Thinking syntax is invalid
  • Believing size must be block
  • Ignoring shared reference issue

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes