0
0
Rubyprogramming~5 mins

Included hook in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Included hook
O(n)
Understanding Time Complexity

We want to understand how the time cost changes when Ruby runs code using the included hook.

Specifically, how does adding this hook affect the work done as the program grows?

Scenario Under Consideration

Analyze the time complexity of this Ruby module using the included hook.

module Greetings
  def self.included(base)
    base.extend(ClassMethods)
  end

  module ClassMethods
    def say_hello
      puts "Hello!"
    end
  end
end

class Person
  include Greetings
end

Person.say_hello

This code adds class methods to a class when the module is included using the included hook.

Identify Repeating Operations

Look for loops or repeated actions in the code.

  • Primary operation: The included hook runs once per class that includes the module.
  • How many times: Exactly once for each class that uses include Greetings.
How Execution Grows With Input

Imagine adding more classes that include the module.

Number of Classes (n)Approx. Operations
1010 times the hook runs
100100 times the hook runs
10001000 times the hook runs

Each new class that includes the module triggers the hook once, so work grows directly with the number of classes.

Final Time Complexity

Time Complexity: O(n)

This means the time grows linearly with how many classes include the module.

Common Mistake

[X] Wrong: "The included hook runs once and then never again no matter how many classes include the module."

[OK] Correct: The hook runs every time a new class includes the module, so it runs once per class, not just once total.

Interview Connect

Understanding how hooks like included run helps you explain how Ruby modules add behavior efficiently as programs grow.

Self-Check

What if the included hook added methods by looping over a large list each time? How would that change the time complexity?