0
0
Rubyprogramming~20 mins

Dig method for nested access in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Dig Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
1: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 result
A42
Bnil
CError: NoMethodError
D0
Attempts:
2 left
💡 Hint
Think about how dig accesses nested keys safely.
Predict Output
intermediate
1: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' : result
Anil
B10
CError: KeyError
Dfalse
Attempts:
2 left
💡 Hint
dig returns nil if any key in the chain is missing.
🔧 Debug
advanced
2: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 result
ASyntaxError due to wrong dig usage
BKeyError because :c is missing
CReturns nil safely
DNoMethodError because dig tries to call :c on nil
Attempts:
2 left
💡 Hint
Consider what happens when dig encounters a nil value before the last key.
🧠 Conceptual
advanced
1: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'}]}
A"Alice"
B"Bob"
Cnil
DError: TypeError
Attempts:
2 left
💡 Hint
Remember dig can access array elements by index.
Predict Output
expert
2: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' : result
Anil
B3
CError: NoMethodError
D1
Attempts:
2 left
💡 Hint
Check what happens when dig tries to access a key on a nil element inside an array.