Yield to execute blocks in Ruby - Time & Space Complexity
We want to understand how the time taken by Ruby code using yield changes as input grows.
Specifically, how often the block runs affects the total work done.
Analyze the time complexity of the following code snippet.
def repeat_times(n)
i = 0
while i < n
yield i
i += 1
end
end
repeat_times(5) { |x| puts x }
This code runs a block of code n times, passing the current count each time.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
whileloop runsntimes, each time callingyieldto run the block. - How many times: Exactly
ntimes, wherenis the input number.
As n grows, the block runs more times, so total work grows in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 calls to the block |
| 100 | About 100 calls to the block |
| 1000 | About 1000 calls to the block |
Pattern observation: The work grows evenly as n grows; doubling n doubles the work.
Time Complexity: O(n)
This means the time taken grows in a straight line with the input size.
[X] Wrong: "Using yield makes the code run instantly or in constant time regardless of n."
[OK] Correct: Each yield runs the block once, so if the block runs many times, total time grows with n.
Understanding how blocks and yield affect time helps you explain code efficiency clearly and confidently.
"What if the block itself contains a loop that runs m times? How would the time complexity change?"