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?✗ Incorrect
dig returns nil if any key in the chain is missing.Which of these is a correct use of
dig to access nested data?✗ Incorrect
dig takes multiple keys and safely returns nested values.Can
dig be used to access elements inside arrays?✗ Incorrect
dig works with arrays by passing numeric indexes.What is the main advantage of using
dig over chaining [] calls?✗ Incorrect
dig safely returns nil instead of raising errors.What will
[{a: 1}].dig(0, :a) return?✗ Incorrect
The first element is a hash with key
:a, so dig returns 1.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.