Times method for counted repetition in Ruby - Time & Space Complexity
We want to understand how the time it takes to run code changes when we use Ruby's times method.
Specifically, how does repeating an action a certain number of times affect the total work done?
Analyze the time complexity of the following code snippet.
5.times do |i|
puts "Count: #{i}"
end
This code repeats a simple print action 5 times, counting from 0 to 4.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The block inside
timesruns once per count. - How many times: Exactly as many times as the number given to
times(here, 5 times).
When the number given to times grows, the number of repeated actions grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 actions |
| 100 | 100 actions |
| 1000 | 1000 actions |
Pattern observation: The total work grows directly in step with the input number.
Time Complexity: O(n)
This means if you double the number of times, the work roughly doubles too.
[X] Wrong: "The times method runs in constant time no matter the number."
[OK] Correct: Each repetition runs the block once, so more repetitions mean more work.
Understanding how repeating actions affect time helps you explain how loops work in real code.
"What if we replaced times with a nested times inside another times? How would the time complexity change?"