Hash methods (keys, values, each) in Ruby - Time & Space Complexity
When we use hash methods like keys, values, and each, we want to know how long these actions take as the hash grows.
We ask: How does the time to run these methods change when the hash has more items?
Analyze the time complexity of the following code snippet.
my_hash = {a: 1, b: 2, c: 3, d: 4}
keys = my_hash.keys
values = my_hash.values
my_hash.each do |key, value|
puts "Key: #{key}, Value: #{value}"
end
This code gets all keys, all values, and then prints each key-value pair from the hash.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Traversing all items in the hash.
- How many times: Once for each method call, it goes through every key-value pair.
Each method looks at every item in the hash one time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps |
| 100 | About 100 steps |
| 1000 | About 1000 steps |
Pattern observation: The work grows directly with the number of items. Double the items, double the work.
Time Complexity: O(n)
This means the time to run these methods grows in a straight line with the number of items in the hash.
[X] Wrong: "Hash methods like keys or values are instant no matter how big the hash is."
[OK] Correct: These methods must look at every item to collect keys or values, so they take longer as the hash grows.
Understanding how hash methods scale helps you write efficient code and explain your choices clearly in interviews.
"What if we used each_key instead of keys? How would the time complexity change?"