Challenge - 5 Problems
Dig Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate1:30remaining
Output of dig with nested hashes
What is the output of this Ruby code using
dig on nested hashes?Ruby
data = {a: {b: {c: 42}}}
result = data.dig(:a, :b, :c)
puts resultAttempts:
2 left
💡 Hint
Think about how dig accesses nested keys safely.
✗ Incorrect
The dig method safely navigates nested hashes and returns the value at the deepest key if it exists. Here, :a, :b, and :c keys exist, so it returns 42.
❓ Predict Output
intermediate1:30remaining
Result of dig when key is missing
What does this Ruby code print when using
dig with a missing key?Ruby
data = {x: {y: 10}}
result = data.dig(:x, :z)
puts result.nil? ? 'nil' : resultAttempts:
2 left
💡 Hint
dig returns nil if any key in the chain is missing.
✗ Incorrect
Since :z key does not exist inside :x, dig returns nil instead of raising an error.
🔧 Debug
advanced2:00remaining
Why does this dig call raise an error?
This Ruby code raises an error. What is the cause?
Ruby
data = {a: {b: nil}}
result = data.dig(:a, :b, :c)
puts resultAttempts:
2 left
💡 Hint
Consider what happens when dig encounters a nil value before the last key.
✗ Incorrect
dig calls the next key on the value of :b, which is nil. Calling dig on nil causes NoMethodError.
🧠 Conceptual
advanced1:30remaining
Understanding dig with arrays and hashes
Given this Ruby data structure, what does
data.dig(:users, 1, :name) return?Ruby
data = {users: [{name: 'Alice'}, {name: 'Bob'}, {name: 'Carol'}]}Attempts:
2 left
💡 Hint
Remember dig can access array elements by index.
✗ Incorrect
dig accesses :users key (an array), then index 1 (second element), then :name key, which is "Bob".
❓ Predict Output
expert2:00remaining
Output of dig with mixed nested structures and nil
What is the output of this Ruby code using dig on mixed nested hashes and arrays with nil values?
Ruby
data = {a: [{b: 1}, nil, {b: 3}]}
result = data.dig(:a, 1, :b)
puts result.nil? ? 'nil' : resultAttempts:
2 left
💡 Hint
Check what happens when dig tries to access a key on a nil element inside an array.
✗ Incorrect
The second element in :a array is nil, so dig tries to call dig(:b) on nil, which raises NoMethodError.