0
0
Rubyprogramming~20 mins

Default values for missing keys in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Hash Default Values Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Ruby code with default hash values?

Consider the following Ruby code that uses a hash with a default value. What will be printed?

Ruby
h = Hash.new(0)
h[:a] += 1
h[:b] += 2
puts h[:a]
puts h[:b]
puts h[:c]
A
1
2
0
B
1
2
nil
C
0
0
0
D
1
2
2
Attempts:
2 left
💡 Hint

Remember that the default value is returned for missing keys but does not get stored in the hash unless assigned.

Predict Output
intermediate
2:00remaining
What happens when using a block for default values in Ruby hash?

What will this Ruby code print?

Ruby
h = Hash.new { |hash, key| hash[key] = [] }
h[:x] << 1
h[:y] << 2
puts h[:x].inspect
puts h[:y].inspect
puts h[:z].inspect
A
[1]
[2]
[1]
B
[1]
[2]
[]
C
[1]
[2]
nil
D
[]
[]
[]
Attempts:
2 left
💡 Hint

Using a block for default values allows the hash to assign a new object for missing keys.

🔧 Debug
advanced
2:30remaining
Why does this Ruby hash with default array behave unexpectedly?

Look at this Ruby code:

h = Hash.new([])
h[:a] << 1
h[:b] << 2
puts h[:a].inspect
puts h[:b].inspect
puts h.inspect

What is the output and why?

A
[1, 2]
[1, 2]
{}
Because the default array is shared for all missing keys.
B
[]
[]
{}
Because the default array is empty and not modified.
C
[1]
[2]
{:a=&gt;[1], :b=&gt;[2]}
Because each key gets its own array.
D
[1]
[1]
{:a=&gt;[1], :b=&gt;[1]}
Because the default array is copied for each key.
Attempts:
2 left
💡 Hint

Think about whether the default object is shared or duplicated for each key.

📝 Syntax
advanced
1:30remaining
Which Ruby hash default value syntax is correct?

Which of the following Ruby hash initializations correctly sets a default value of 10 for missing keys?

Ah = Hash.new { |h, k| 10 }
Bh = Hash.new { 10 }
Ch = Hash.new(10)
Dh = Hash.new { |h, k| h[k] = 10 }
Attempts:
2 left
💡 Hint

Only one option assigns the default value to the key in the hash.

🚀 Application
expert
2:30remaining
How many keys are in the hash after this Ruby code runs?

Given this Ruby code:

h = Hash.new { |hash, key| hash[key] = key * 2 }
h[1]
h[2]
h[3]
count = h.size

What is the value of count after running this code?

A1
B0
C3
D2
Attempts:
2 left
💡 Hint

Accessing a missing key with a block default assigns a value to that key.