Bird
0
0

What will be the output of the following Ruby code?

medium📝 Predict Output Q5 of 15
Ruby - Arrays
What will be the output of the following Ruby code?
arr = Array.new(3, Hash.new)
arr[0][:key] = 'value'
puts arr.inspect
A[{}, {}, {}]
B[{:key=>"value"}, {:key=>"value"}, {:key=>"value"}]
C[{:key=>"value"}, {}, {}]
D[{}, {:key=>"value"}, {}]
Step-by-Step Solution
Solution:
  1. Step 1: Understand Array.new with a shared object

    Using Array.new(3, Hash.new) creates an array with 3 references to the same hash object.
  2. Step 2: Modify one element

    When arr[0][:key] = 'value' is executed, it modifies the single shared hash object.
  3. Final Answer:

    [{:key=>"value"}, {:key=>"value"}, {:key=>"value"}] -> Option B
  4. Quick Check:

    All elements point to the same hash, so all show the change. [OK]
Quick Trick: Array.new with object shares same reference [OK]
Common Mistakes:
  • Assuming each element is a separate hash
  • Expecting only first element to change
  • Confusing with block form of Array.new

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes