Bird
0
0

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:
  1. Step 1: Understand unique hash creation

    Using block form with index allows creating unique hashes with different :id values.
  2. 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.
  3. Final Answer:

    Array.new(4) { |i| { id: i + 1 } } -> Option C
  4. 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes