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?"
Practice
private method in Ruby?Solution
Step 1: Understand private method access
Private methods in Ruby are only accessible within the same object, meaning you cannot call them on other instances, even if they belong to the same class.Step 2: Compare with other visibility levels
Protected methods allow access from other instances of the same class or subclasses, but private methods do not.Final Answer:
It can only be called within the same object, not even by other instances of the same class. -> Option BQuick Check:
Private = same object only [OK]
- Thinking private methods can be called on other instances
- Confusing private with protected visibility
- Assuming private methods are accessible outside the class
Solution
Step 1: Recall Ruby private method syntax
In Ruby, you declare private methods by writingprivateon its own line, then defining the method below it.Step 2: Check each option
privateon its own line followed bydef method_name endis correct syntax. Puttingprivateon the same line asdef, prefixingdefwithprivate, or placingprivateinside the method are invalid.Final Answer:
private def method_name end -> Option AQuick Check:
private keyword on separate line before method [OK]
- Trying to put 'private' inside method definition line
- Using 'private def' which is invalid syntax
- Placing 'private' after method definition
class Person
protected
def secret
"protected info"
end
public
def reveal_secret(other)
other.secret
end
end
p1 = Person.new
p2 = Person.new
puts p1.reveal_secret(p2)Solution
Step 1: Understand protected method access
Protected methods can be called by other instances of the same class. Here,p1callsreveal_secretpassingp2, and inside it callsother.secret.Step 2: Predict output
Sincesecretis protected,p1can callsecretonp2. The method returns "protected info", which is printed.Final Answer:
protected info -> Option CQuick Check:
Protected allows calls between same class instances [OK]
- Thinking protected methods can't be called on other instances
- Expecting NoMethodError for protected method call
- Confusing protected with private access
class Animal
private
def sound
"roar"
end
def make_sound(other)
other.sound
end
end
lion = Animal.new
tiger = Animal.new
puts lion.make_sound(tiger)Solution
Step 1: Understand private method restrictions
Private methods cannot be called with an explicit receiver, even if the receiver is an instance of the same class.Step 2: Analyze the method call
Inmake_sound,other.soundcalls a private method on another instance, which is not allowed and raises NoMethodError.Final Answer:
NoMethodError: private method `sound' called for tiger -> Option AQuick Check:
Private methods can't be called on other instances [OK]
- Assuming private methods can be called on other instances
- Confusing private and protected method rules
- Expecting no error when calling private method on other object
class User
# Your code here
def compare_password(other)
self.password == other.password
end
private
def password
"secret123"
end
end
u1 = User.new
u2 = User.new
puts u1.compare_password(u2)Solution
Step 1: Understand method visibility for inter-instance calls
Private methods cannot be called with an explicit receiver, soother.passwordwill fail ifpasswordis private.Step 2: Use protected visibility
Protected methods allow calls between instances of the same class, so changingpasswordto protected allowsother.passwordto work while keeping it hidden from outside.Final Answer:
Makepassworda protected method; private won't allowother.passwordcall. -> Option DQuick Check:
Protected allows inter-instance calls, private does not [OK]
- Keeping password private and expecting inter-instance calls to work
- Making password public and exposing sensitive data
- Using attr_accessor without protection
Ready to prove it?
Pass the test and this pattern moves unknown
