Case/when statement in Ruby - Time & Space Complexity
We want to understand how long a case/when statement takes to run as the input changes.
Specifically, how does the number of checks grow when we have more conditions?
Analyze the time complexity of the following code snippet.
case value
when 1
puts "One"
when 2
puts "Two"
when 3
puts "Three"
else
puts "Other"
end
This code checks the value against several conditions and prints a message for the first match.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking each condition one by one until a match is found.
- How many times: Up to the number of conditions (here 3), but stops early if matched.
As the number of conditions grows, the checks increase roughly one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 3 | Up to 3 checks |
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
Pattern observation: The number of checks grows directly with the number of conditions.
Time Complexity: O(n)
This means the time to find a match grows linearly with the number of conditions.
[X] Wrong: "The case statement always runs in constant time no matter how many conditions there are."
[OK] Correct: The case statement checks conditions one by one, so more conditions mean more checks and longer time.
Understanding how case/when scales helps you explain how your code behaves with many conditions, a useful skill in real projects.
"What if we replaced the case/when with a hash lookup? How would the time complexity change?"