Table of contentsClick link to navigate to the desired location
This content has been automatically translated from Ukrainian.
In Ruby, it is easy to get confused when it comes to access levels for methods - especially in cases involving self. At first glance, protected and private seem similar, but the difference manifests in how Ruby interprets calls through self.
In Ruby, any method can be called in two ways:
do_something # without self self.do_something # with self
public - methods are always accessibleprotected - accessible only for objects of the same class or subclassprivate - accessible only without an explicit receiver (self)
private - cannot be called through self
Private methods are methods that can only be called "from within themselves". Ruby does not allow specifying a receiver (self), even if it is the same object.
class User
def greet
self.secret_message # cannot
end
def greet_ok
secret_message # can
end
private
def secret_message
"Hello from private"
end
end
user = User.new
user.greet_ok # => "Hello from private"
user.greet # => NoMethodError
private restricts calls only in the context of the current object, without explicit self.
protected - can be called through self, but only among objects of the same class
Unlike private, protected methods allow calls through self or another instance, as long as they belong to the same class or subclass.
class User
def initialize(age)
@age = age
end
def older_than?(other)
self.age > other.age # can through self
end
protected
def age
@age
end
end
u1 = User.new(30)
u2 = User.new(20)
u1.older_than?(u2) # => true
protected is often used when you need to compare or interact between instances of the same class, but not provide access to external code.
public - without restrictions
Public methods are always accessible, both with self and without it.
class User
def greet
self.name
end
def name
"Marian"
end
end
User.new.greet # => "Marian"
In summary
- public - methods are accessible to everyone.
- protected - methods can be called through self and between instances of the same class.
- private - methods can only be called without self, within the current object.
To remember all this - create an rb file locally and experiment with the code. Only through practice can you truly grasp the difference.
This post doesn't have any additions from the author yet.