Everything is an object mental model in Ruby - Time & Space Complexity
When we say "everything is an object" in Ruby, it means every value and data type behaves like an object. This affects how operations run because method calls happen on these objects.
We want to understand how the time to run code grows when using objects and their methods.
Analyze the time complexity of the following Ruby 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 creates a Box object holding a list and counts how many items it has by calling a method on the object.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling the
lengthmethod on the array inside the object. - How many times: The method is called once, and internally it accesses the stored length.
Counting items grows as the list gets bigger, but Ruby stores the length, so it does not count each time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 (direct access) |
| 100 | 1 (direct access) |
| 1000 | 1 (direct access) |
Pattern observation: The operation stays constant no matter how big the list is because length is stored, not counted each time.
Time Complexity: O(1)
This means counting items in the object takes the same time no matter how many items there are.
[X] Wrong: "Calling a method on an object always means going through all items inside it."
[OK] Correct: Some methods like length just read stored information, so they run quickly without checking every item.
Understanding that everything is an object helps you think clearly about how Ruby runs code. It shows you when operations are quick or might take longer, which is useful for writing efficient programs.
"What if the count_items method counted items by looping through the list instead of using length? How would the time complexity change?"