Extend for class methods in Ruby - Time & Space Complexity
We want to understand how adding class methods using extend affects the time it takes to run code.
How does the program's work grow when we add methods this way?
Analyze the time complexity of the following code snippet.
module Greetings
def hello
"Hello!"
end
end
class Person
extend Greetings
end
Person.hello
This code adds a class method hello to Person by extending it with the Greetings module.
Look for loops or repeated steps in the code.
- Primary operation: Adding methods to a class using
extendhappens once. - How many times: The extension runs only once when the class is defined or extended.
Adding methods with extend does not depend on input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Constant steps to add methods |
| 100 | Same constant steps |
| 1000 | Still constant steps |
Pattern observation: The work stays the same no matter how many times you call the method later.
Time Complexity: O(1)
This means adding class methods with extend takes the same small amount of time regardless of input size.
[X] Wrong: "Extending a class with many methods makes the program slower every time I call those methods."
[OK] Correct: The extension happens once when setting up the class, not each time you call the methods. Calling the methods later runs only their own code.
Knowing how extend works helps you explain how Ruby adds class methods efficiently. This shows you understand how Ruby organizes code behind the scenes.
"What if we used include instead of extend? How would the time complexity change when adding methods?"