0
0
Rubyprogramming~5 mins

Conditional assignment (||=) in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Conditional assignment (||=)
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations
  • Primary operation: Looping through each key-value pair in the hash.
  • How many times: Once for each item in the hash (n times).
How Execution Grows With Input

As the number of items in the hash grows, the program checks each item once.

Input Size (n)Approx. Operations
10About 10 checks and possible assignments
100About 100 checks and possible assignments
1000About 1000 checks and possible assignments

Pattern observation: The work grows directly with the number of items, so doubling items doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the program takes longer in a straight line as the input size grows.

Common Mistake

[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.

Interview Connect

Understanding how conditional assignment affects performance helps you explain your code choices clearly and shows you know how programs scale.

Self-Check

"What if we replaced the hash with an array and used ||= inside a nested loop? How would the time complexity change?"