You want to create an array of 4 unique hashes, each with a key :id and values 1 to 4. Which code correctly does this?
hard📝 Application Q8 of 15
Ruby - Arrays
You want to create an array of 4 unique hashes, each with a key :id and values 1 to 4. Which code correctly does this?
AArray.new(4) { { id: 1 } }
BArray.new(4, { id: 1 })
CArray.new(4) { |i| { id: i + 1 } }
D[{ id: 1 }] * 4
Step-by-Step Solution
Solution:
Step 1: Understand unique hash creation
Using block form with index allows creating unique hashes with different :id values.
Step 2: Check options
A creates unique hashes but all with id:1. B shares the same hash object. C with [{ id: 1 }] * 4 references the same hash multiple times. Only D uses index for unique values 1-4.
Final Answer:
Array.new(4) { |i| { id: i + 1 } } -> Option C
Quick Check:
Block form creates unique hashes with varying values [OK]
Quick Trick:Use block with index for unique complex elements [OK]
Common Mistakes:
Using default object for hashes
Creating identical hashes
Not using index for values
Master "Arrays" in Ruby
9 interactive learning modes - each teaches the same concept differently