Included hook in Ruby - Time & Space 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?
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.
Look for loops or repeated actions in the code.
- Primary operation: The
includedhook runs once per class that includes the module. - How many times: Exactly once for each class that uses
include Greetings.
Imagine adding more classes that include the module.
| Number of Classes (n) | Approx. Operations |
|---|---|
| 10 | 10 times the hook runs |
| 100 | 100 times the hook runs |
| 1000 | 1000 times the hook runs |
Each new class that includes the module triggers the hook once, so work grows directly with the number of classes.
Time Complexity: O(n)
This means the time grows linearly with how many classes include the module.
[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.
Understanding how hooks like included run helps you explain how Ruby modules add behavior efficiently as programs grow.
What if the included hook added methods by looping over a large list each time? How would that change the time complexity?