Accessing parent methods in Ruby - Time & Space Complexity
When a child class calls a method from its parent class, it runs some code inherited from above. We want to see how the time it takes changes as the input grows.
How does calling a parent method affect the total work done?
Analyze the time complexity of the following code snippet.
class Parent
def process(items)
items.each do |item|
puts item * 2
end
end
end
class Child < Parent
def process(items)
super
end
end
child = Child.new
child.process([1, 2, 3, 4, 5])
This code defines a parent class with a method that loops over a list and prints doubled values. The child class calls the parent's method using super.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping over each item in the list inside the parent method.
- How many times: Once for each item in the input array.
As the list gets bigger, the method runs the loop more times, doing more work.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 times printing doubled values |
| 100 | 100 times printing doubled values |
| 1000 | 1000 times printing doubled values |
Pattern observation: The work grows directly with the number of items. Double the items, double the work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items in the list.
[X] Wrong: "Calling super adds extra loops or doubles the work."
[OK] Correct: The child just calls the parent's method once. It does not repeat the loop multiple times, so the work stays proportional to the input size.
Understanding how inherited methods run helps you explain code efficiency clearly. It shows you can think about how code layers affect performance, a useful skill in many coding tasks.
What if the child method added another loop over the items before calling super? How would the time complexity change?