Bird
0
0

How can you create an array of 5 hashes, each with keys :a and :b initialized to 0, ensuring each hash is a separate object?

hard📝 Application Q15 of 15
Ruby - Arrays
How can you create an array of 5 hashes, each with keys :a and :b initialized to 0, ensuring each hash is a separate object?
A<code>Array(5) { {a: 0, b: 0} }</code>
B<code>Array.new(5, {a: 0, b: 0})</code>
C<code>[{a: 0, b: 0}] * 5</code>
D<code>Array.new(5) { {a: 0, b: 0} }</code>
Step-by-Step Solution
Solution:
  1. Step 1: Understand object references in Array.new

    Using Array.new(5, {a: 0, b: 0}) or [{a: 0, b: 0}] * 5 repeats the same hash object 5 times.
  2. Step 2: Use block form for unique hashes

    Using Array.new(5) { {a: 0, b: 0} } runs the block 5 times, creating 5 separate hashes.
  3. Final Answer:

    Array.new(5) { {a: 0, b: 0} } -> Option D
  4. Quick Check:

    Block form creates unique objects [OK]
Quick Trick: Use block with Array.new for unique hashes [OK]
Common Mistakes:
  • Using Array.new with default hash causes shared references
  • Using multiplication operator with arrays of hashes
  • Trying invalid Array() constructor syntax

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes