Table of contentsClick link to navigate to the desired location
This content has been automatically translated from Ukrainian.
Ruby is easy to get confused when it comes to access levels to methods - especially in self cases. At first glance, protected and private seem similar, but the difference is precisely how Ruby interprets challenges 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 availableprotected - Available only for objects of the same class or subclassprivate - available only without an explicit recipient (self)
private - cannot be called through self
Private methods are methods that can only be invoked "within oneself". Ruby does not allow the recipient (self) to be specified, 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 limits the call only in the context of the current object, without explicit self.
protected - can be called via self, but only among objects of the same class
Unlike private, protected methods allow calls via self or another instance if 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 be done through self
end
protected
def age
@age
end
end
u1 = User.new(30)
u2 = User.new(20)
u1.older_than?(u2) # => true
protected 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 available, both with and without self.
class User
def greet
self.name
end
def name
"Marian"
end
end
User.new.greet # => "Marian"
In short
- public - methods are available to everyone.
- protected - methods can be called via self and between instances of the same class.
- private - Methods can only be called without self, inside the current object.
To remember this whole thing - create an rb file locally and experiment with the code. Only in practice can you learn the difference well.
This post doesn't have any additions from the author yet.