Inherited hook in Ruby - Time & Space Complexity
When Ruby classes inherit from each other, the inherited hook runs. We want to see how the time it takes to run this hook changes as more classes inherit.
How does the number of inherited classes affect the total work done by the hook?
Analyze the time complexity of the following Ruby code using the inherited hook.
class Parent
def self.inherited(subclass)
puts "New subclass: #{subclass}"
end
end
class Child1 < Parent; end
class Child2 < Parent; end
class Child3 < Parent; end
This code prints a message every time a new subclass inherits from Parent.
Look at what repeats when new subclasses are created.
- Primary operation: The
inheritedmethod runs once for each subclass. - How many times: Once per subclass created, so if there are
nsubclasses, it runsntimes.
As the number of subclasses grows, the total times the hook runs grows the same way.
| Input Size (n subclasses) | Approx. Operations (hook calls) |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The work grows directly with the number of subclasses.
Time Complexity: O(n)
This means the total work done by the inherited hook grows in a straight line with the number of subclasses.
[X] Wrong: "The inherited hook runs only once no matter how many subclasses there are."
[OK] Correct: The hook runs every time a new subclass is created, so it runs as many times as subclasses exist.
Understanding how hooks like inherited scale helps you reason about code that runs automatically during class creation. This skill shows you can think about hidden costs in programs.
What if the inherited hook also created a new subclass inside itself? How would that affect the time complexity?