Bird
0
0

Which of the following is the correct syntax to create a Ruby hash with a default value of an empty array for missing keys?

easy📝 Syntax Q12 of 15
Ruby - Hashes
Which of the following is the correct syntax to create a Ruby hash with a default value of an empty array for missing keys?
Ah = Hash.new { |key| [] }
Bh = Hash.new { [] }
Ch = Hash.new([])
Dh = Hash.new { |hash, key| hash[key] = [] }
Step-by-Step Solution
Solution:
  1. Step 1: Understand default block usage

    Using a block with Hash.new allows dynamic default values. To assign a new array to each missing key, the block must assign it to the hash.
  2. Step 2: Identify correct block syntax

    The block receives hash and key parameters and assigns [] to hash[key]. This ensures each missing key gets its own array.
  3. Final Answer:

    h = Hash.new { |hash, key| hash[key] = [] } -> Option D
  4. Quick Check:

    Block assigns new array to missing keys [OK]
Quick Trick: Use block with two params to assign default arrays [OK]
Common Mistakes:
  • Using Hash.new([]) shares one array for all keys
  • Using block without assigning to hash[key]
  • Using wrong block parameters

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes