0
0
Rubyprogramming~5 mins

Block given? check in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Block given? check
O(1)
Understanding Time 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?

Scenario Under Consideration

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

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.
How Execution Grows With Input

Checking if a block is given does not depend on the size of the input.

Input Size (n)Approx. Operations
101 check
1001 check
10001 check

Pattern observation: The number of operations stays the same no matter how big the input is.

Final Time Complexity

Time Complexity: O(1)

This means the time to check if a block is given stays constant regardless of input size.

Common Mistake

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

Interview Connect

Understanding simple checks like block_given? helps you explain how small parts of code behave in terms of speed.

Self-Check

"What if the method called the block multiple times inside a loop? How would the time complexity change?"