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?"
Practice
yield keyword do in a Ruby method?Solution
Step 1: Understand the role of
Theyieldyieldkeyword is used inside a method to call the block that was passed to that method.Step 2: Differentiate from other keywords
Unlikereturnor method definitions,yieldspecifically executes the block given to the method.Final Answer:
It runs the block of code passed to the method. -> Option AQuick Check:
Yield executes block = A [OK]
- Thinking yield returns method value
- Confusing yield with return
- Assuming yield defines a method
yield with an argument inside a method?Solution
Step 1: Recall yield syntax with arguments
To pass arguments to the block,yieldmust be called with parentheses around the arguments, likeyield(5).Step 2: Check other options for syntax errors
Options B, C, and D are incorrect because they either miss parentheses or use invalid syntax.Final Answer:
def example; yield(5); end -> Option AQuick Check:
Yield with args uses parentheses = A [OK]
- Omitting parentheses when passing arguments
- Using assignment (=) with yield
- Using colon (:) instead of parentheses
def greet
yield("Alice")
end
greet { |name| puts "Hello, #{name}!" }Solution
Step 1: Understand yield with argument
The methodgreetcallsyieldwith the string "Alice" as argument, passing it to the block.Step 2: Evaluate the block execution
The block receives "Alice" asnameand prints "Hello, Alice!".Final Answer:
Hello, Alice! -> Option BQuick Check:
Yield passes "Alice" to block = C [OK]
- Ignoring the argument passed to yield
- Assuming block is not called
- Confusing variable names in block
def run_block
yield if block_given
end
run_block { puts "Block executed" }Solution
Step 1: Check usage of block_given?
The method to check if a block is given isblock_given?, note the question mark.Step 2: Identify the error in code
The code usesblock_givenwithout the question mark (?), which causes a NameError becauseblock_givenis not a valid method.Final Answer:
Missing question mark (?) in block_given? method call -> Option DQuick Check:
Use block_given? with question mark [OK]
- Forgetting question mark (?) on block_given?
- Assuming yield needs arguments always
- Not passing a block when expected
def repeat(n)
if block_given?
n.times { |i| yield(i) }
else
puts "No block given"
end
end
repeat(3) { |num| puts num * 2 }Solution
Step 1: Analyze the method behavior
The methodrepeatchecks if a block is given. Since a block is passed, it runsn.timesand yields the indexito the block.Step 2: Evaluate the block execution
The block multiplies each yielded number by 2 and prints it. Forn=3,igoes 0,1,2, so outputs are 0, 2, 4.Final Answer:
0 2 4 -> Option CQuick Check:
Yield with times and block multiplies index = D [OK]
- Confusing index values starting at 1
- Ignoring block_given? check
- Expecting output without block
Ready to prove it?
Pass the test and this pattern moves unknown
