Case with ranges and patterns in Ruby - Time & Space Complexity
We want to understand how long it takes for a Ruby case statement using ranges and patterns to run as the input changes.
Specifically, how does the time grow when checking multiple conditions with ranges?
Analyze the time complexity of the following code snippet.
score = 75
case score
when 0..59
puts "Fail"
when 60..69
puts "Pass"
when 70..79
puts "Good"
when 80..89
puts "Very Good"
else
puts "Excellent"
end
This code checks which range the score falls into and prints a message accordingly.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking the input against each range in the case statement.
- How many times: Each range is checked one by one until a match is found or all are checked.
As the number of ranges grows, the number of checks grows too, because each range is tested in order.
| Input Size (number of ranges) | Approx. Operations (checks) |
|---|---|
| 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 ranges to test.
Time Complexity: O(n)
This means the time to find the matching range grows linearly with how many ranges there are.
[X] Wrong: "The case statement checks all ranges at once, so time stays the same no matter how many ranges there are."
[OK] Correct: Actually, Ruby checks each range one by one until it finds a match, so more ranges mean more checks and more time.
Understanding how case statements with ranges work helps you reason about condition checks in real code, which is a useful skill for writing efficient programs.
"What if we changed the case statement to use a hash lookup instead of ranges? How would the time complexity change?"