0
0
Rubyprogramming~5 mins

Yield to execute blocks in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Yield to execute blocks
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The while loop runs n times, each time calling yield to run the block.
  • How many times: Exactly n times, where n is the input number.
How Execution Grows With Input

As n grows, the block runs more times, so total work grows in direct proportion.

Input Size (n)Approx. Operations
10About 10 calls to the block
100About 100 calls to the block
1000About 1000 calls to the block

Pattern observation: The work grows evenly as n grows; doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time taken grows in a straight line with the input size.

Common Mistake

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

Interview Connect

Understanding how blocks and yield affect time helps you explain code efficiency clearly and confidently.

Self-Check

"What if the block itself contains a loop that runs m times? How would the time complexity change?"