Bird
0
0

What issue arises from this Ruby code?

medium📝 Debug Q6 of 15
Ruby - Arrays
What issue arises from this Ruby code?
arr = Array.new(2, [])
arr[0] << 10
arr[1].clear
puts arr.inspect
Aarr[1].clear only affects the second element
BBoth elements refer to the same array, so clearing one clears both
CThe code raises a runtime error due to modifying frozen array
DEach element is a separate array, so no issue occurs
Step-by-Step Solution
Solution:
  1. Step 1: Analyze Array.new with default object

    Array.new(2, []) creates an array with two references to the same empty array.
  2. Step 2: Modify one element

    arr[0] << 10 adds 10 to the shared array.
  3. Step 3: Clear second element

    arr[1].clear empties the same shared array, affecting both elements.
  4. Final Answer:

    Both elements refer to the same array, so clearing one clears both -> Option B
  5. Quick Check:

    Shared references cause unexpected side effects. [OK]
Quick Trick: Array.new with object shares same reference [OK]
Common Mistakes:
  • Assuming elements are independent arrays
  • Expecting clear to affect only one element
  • Not recognizing shared object reference

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes