Dig method for nested access in Ruby - Time & Space Complexity
We want to understand how the time needed to find a value inside nested data grows as the data gets bigger.
How does using the dig method affect the time it takes to reach the value?
Analyze the time complexity of the following code snippet.
data = { a: { b: { c: 1 } } }
value = data.dig(:a, :b, :c)
This code uses dig to get a deeply nested value inside hashes.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Accessing each nested key one by one.
- How many times: Once for each key in the dig argument list.
Each extra key means one more step to look inside the nested data.
| Input Size (n) | Approx. Operations |
|---|---|
| 3 keys | 3 steps |
| 10 keys | 10 steps |
| 100 keys | 100 steps |
Pattern observation: The time grows directly with the number of keys you dig through.
Time Complexity: O(n)
This means the time to get the value grows in a straight line with the number of nested keys.
[X] Wrong: "Digging into nested data is instant no matter how deep."
[OK] Correct: Each extra level means one more step to check, so deeper nesting takes more time.
Knowing how digging into nested data scales helps you write clear and efficient code when working with complex data structures.
"What if the nested data was stored in arrays instead of hashes? How would the time complexity of dig change?"