Instance methods in Ruby - Time & Space Complexity
When we use instance methods in Ruby, we want to know how long they take to run as the input changes.
We ask: How does the time to run an instance method grow when the data it works on gets bigger?
Analyze the time complexity of the following code snippet.
class Box
def initialize(items)
@items = items
end
def count_items
@items.length
end
end
box = Box.new([1, 2, 3, 4, 5])
puts box.count_items
This code defines a class with an instance method that returns the number of items stored inside.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Accessing the length of the array stored in the instance variable.
- How many times: The length method runs once per call to
count_items.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The time to get the length stays the same no matter how many items there are.
Time Complexity: O(1)
This means the method runs in constant time, taking the same amount of time regardless of input size.
[X] Wrong: "Calling length on an array inside an instance method takes longer as the array grows."
[OK] Correct: Ruby arrays store their length, so getting it is quick and does not depend on the number of items.
Understanding how instance methods work with data size helps you explain your code clearly and think about efficiency in real projects.
"What if the instance method iterated over all items to sum them? How would the time complexity change?"