Block given? check in Ruby - Time & Space Complexity
We want to understand how checking if a block is given affects the time a Ruby method takes to run.
Specifically, we ask: how does this check grow as input changes?
Analyze the time complexity of the following code snippet.
def greet(name)
if block_given?
yield(name)
else
"Hello, #{name}!"
end
end
result = greet("Alice") { |n| "Hi, #{n.upcase}!" }
This method checks if a block is given and either yields to it or returns a greeting string.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The method performs a single check
block_given?once per call. - How many times: Exactly once each time the method runs.
Checking if a block is given does not depend on the size of the input.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 check |
| 100 | 1 check |
| 1000 | 1 check |
Pattern observation: The number of operations stays the same no matter how big the input is.
Time Complexity: O(1)
This means the time to check if a block is given stays constant regardless of input size.
[X] Wrong: "Checking if a block is given takes longer when the input is bigger."
[OK] Correct: The check only looks for a block presence once and does not depend on input size.
Understanding simple checks like block_given? helps you explain how small parts of code behave in terms of speed.
"What if the method called the block multiple times inside a loop? How would the time complexity change?"