0
0
Rubyprogramming~5 mins

Let and before hooks in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Let and before hooks
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run code with let and before hooks changes as the input grows.

How does the setup and repeated use of these hooks affect the total work done?

Scenario Under Consideration

Analyze the time complexity of the following Ruby test setup using let and before hooks.


let(:numbers) { (1..n).to_a }
before do
  @sum = 0
  numbers.each do |num|
    @sum += num
  end
end

it 'calculates sum' do
  expect(@sum).to eq(n * (n + 1) / 2)
end
    

This code creates an array of numbers from 1 to n, sums them before each test, and checks the sum.

Identify Repeating Operations

Look at what repeats when the test runs.

  • Primary operation: Looping through the array to sum numbers.
  • How many times: Once before each test example runs.
How Execution Grows With Input

As n grows, the number of numbers to add grows too.

Input Size (n)Approx. Operations
10About 10 additions
100About 100 additions
1000About 1000 additions

Pattern observation: The work grows directly with n; doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the before hook grows in a straight line as the input size grows.

Common Mistake

[X] Wrong: "The let block runs only once, so it doesn't affect time much."

[OK] Correct: The let block runs lazily once per test example (memoized after first use within the example), so the cost repeats for each test.

Interview Connect

Understanding how setup code like before hooks scales helps you write tests that run efficiently as your project grows.

Self-Check

"What if we moved the summing code inside the let block instead of the before hook? How would the time complexity change?"