Why everything is an object in Ruby - Performance Analysis
We want to understand how Ruby treats all values as objects and what that means for running code.
How does this design affect the steps a program takes as it runs?
Analyze the time complexity of calling a method on different Ruby objects.
def print_class(obj)
puts obj.class
end
print_class(42)
print_class("hello")
print_class([1, 2, 3])
print_class({a: 1, b: 2})
This code calls the class method on various objects to show that all values respond to methods.
Look at what repeats when calling methods on objects.
- Primary operation: Calling a method on an object (like
class). - How many times: Once per call, repeated for each object passed.
Each method call takes a small, fixed number of steps regardless of the object size.
| Input Size (n) | Approx. Operations |
|---|---|
| 1 object | 1 method call |
| 10 objects | 10 method calls |
| 100 objects | 100 method calls |
Pattern observation: The work grows directly with how many objects you call methods on.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of objects you work with.
[X] Wrong: "Since everything is an object, method calls must be slow or complex."
[OK] Correct: Ruby optimizes method calls so they are fast, and treating all values as objects keeps code simple and consistent.
Knowing that everything is an object helps you understand Ruby's design and how method calls scale, which is useful when explaining your code's behavior.
"What if we changed the method call to one that processes the object's contents, like summing an array? How would the time complexity change?"