Hash as named parameters pattern in Ruby - Time & Space Complexity
When using a hash as named parameters in Ruby, it's important to understand how the program's speed changes as the number of parameters grows.
We want to know how the time to find and use these parameters changes when the hash gets bigger.
Analyze the time complexity of the following code snippet.
def greet(options = {})
name = options[:name] || "Guest"
age = options[:age] || 0
city = options[:city] || "Unknown"
"Hello, my name is #{name}, I am #{age} years old, from #{city}."
end
puts greet(name: "Alice", age: 30, city: "Paris")
This code uses a hash to pass named parameters to a method and accesses them inside the method.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Accessing values by keys in the hash.
- How many times: Each key is accessed once per method call.
Each time the method runs, it looks up each key in the hash once.
| Input Size (n) | Approx. Operations |
|---|---|
| 3 | 3 lookups |
| 10 | 10 lookups |
| 100 | 100 lookups |
Pattern observation: The number of operations grows directly with the number of keys accessed.
Time Complexity: O(n)
This means the time to access all parameters grows linearly with how many keys you look up in the hash.
[X] Wrong: "Accessing a value in a hash is slow and depends on the size of the hash."
[OK] Correct: Hash lookups are very fast and usually take the same time no matter how big the hash is, so each key access is quick.
Understanding how named parameters work with hashes and their time cost helps you write clear and efficient Ruby methods, a useful skill in many coding situations.
"What if we changed the hash to a nested hash and accessed keys inside it? How would the time complexity change?"