0
0
Rubyprogramming~5 mins

Dig method for nested access in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the dig method do in Ruby?
The dig method safely accesses nested elements inside hashes or arrays without raising errors if a key or index is missing. It returns nil instead.
Click to reveal answer
beginner
How do you use dig to get a value from a nested hash?
You call dig on the hash and pass the keys in order. For example, hash.dig(:key1, :key2) returns the value inside :key2 nested in :key1.
Click to reveal answer
beginner
What happens if a key or index does not exist when using dig?
Instead of raising an error, dig returns nil. This helps avoid crashes when accessing deep nested data.
Click to reveal answer
intermediate
Can dig be used with arrays as well as hashes?
Yes! You can use dig to access nested arrays by passing indexes along with hash keys. For example, array.dig(0, :key) works if the first element is a hash.
Click to reveal answer
intermediate
Why is dig better than chaining multiple [] calls?
Because chaining [] calls can raise errors if any key or index is missing. dig safely returns nil without crashing, making code cleaner and safer.
Click to reveal answer
What does hash.dig(:a, :b) return if :a exists but :b does not?
ARaises an error
Bnil
CReturns the whole hash
DReturns false
Which of these is a correct use of dig to access nested data?
Ahash.dig(:key1, :key2)
Bhash[:key1][:key2]
Chash.get(:key1, :key2)
Dhash.fetch(:key1).fetch(:key2)
Can dig be used to access elements inside arrays?
AOnly if arrays are converted to hashes
BNo, only hashes
COnly with strings
DYes, by passing indexes as arguments
What is the main advantage of using dig over chaining [] calls?
AIt prints the nested value
BIt runs faster
CIt avoids errors if keys or indexes are missing
DIt modifies the original data
What will [{a: 1}].dig(0, :a) return?
A1
Bnil
CRaises an error
DAn array
Explain how the dig method helps when accessing nested hashes or arrays.
Think about what happens if a key or index is missing.
You got /4 concepts.
    Describe a situation where using dig is better than chaining multiple [] calls.
    Consider what happens if one part of the chain is missing.
    You got /4 concepts.