Protected and private visibility in Ruby - Time & Space Complexity
Let's explore how the time it takes to run code changes when using protected and private methods in Ruby.
We want to see how method visibility affects the number of steps the program takes.
Analyze the time complexity of the following code snippet.
class Person
def initialize(name)
@name = name
end
protected
def greet(other)
"Hello, #{other.send(:name)}!"
end
private
def name
@name
end
end
p1 = Person.new("Alice")
p2 = Person.new("Bob")
puts p1.greet(p2)
This code defines a class with protected and private methods and calls a protected method that uses a private method.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling the protected method
greetwhich internally calls the private methodname. - How many times: Each method is called once per invocation; no loops or recursion here.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 method calls if repeated 10 times |
| 100 | About 100 method calls if repeated 100 times |
| 1000 | About 1000 method calls if repeated 1000 times |
Pattern observation: The number of operations grows directly with how many times you call the methods; each call is simple and does not loop.
Time Complexity: O(n)
This means the time grows in a straight line with the number of method calls; each call takes a fixed small amount of time.
[X] Wrong: "Protected and private methods slow down the program a lot because of visibility checks."
[OK] Correct: Visibility checks add only a tiny fixed cost per call, so they don't change how time grows with input size.
Understanding how method visibility affects performance helps you write clear and efficient code, a skill valued in many programming tasks.
"What if the protected method called itself recursively? How would the time complexity change?"