Conditional assignment (||=) in Ruby - Time & Space Complexity
We want to understand how fast a program runs when it uses conditional assignment with ||= in Ruby.
Specifically, how does the number of steps change as the input grows?
Analyze the time complexity of the following code snippet.
def fill_defaults(data)
data.each do |key, value|
data[key] ||= expensive_computation(key)
end
end
# expensive_computation simulates a costly operation
This code goes through each item in a hash and sets a default value only if the current value is nil or false.
- Primary operation: Looping through each key-value pair in the hash.
- How many times: Once for each item in the hash (n times).
As the number of items in the hash grows, the program checks each item once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks and possible assignments |
| 100 | About 100 checks and possible assignments |
| 1000 | About 1000 checks and possible assignments |
Pattern observation: The work grows directly with the number of items, so doubling items doubles the work.
Time Complexity: O(n)
This means the program takes longer in a straight line as the input size grows.
[X] Wrong: "Using ||= makes the code run faster than looping through all items."
[OK] Correct: The ||= only skips assignment if the value exists, but the loop still checks every item, so the time still grows with input size.
Understanding how conditional assignment affects performance helps you explain your code choices clearly and shows you know how programs scale.
"What if we replaced the hash with an array and used ||= inside a nested loop? How would the time complexity change?"