Public vs Private vs Protected in Ruby: Key Differences and Usage
public methods can be called by anyone, private methods can only be called within the defining class without an explicit receiver, and protected methods can be called by instances of the defining class or its subclasses, but only with an explicit receiver. These control how and where methods are accessible to enforce encapsulation.Quick Comparison
Here is a quick table summarizing the key differences between public, private, and protected methods in Ruby.
| Access Modifier | Who Can Call? | Receiver Allowed? | Default Visibility | Typical Use Case |
|---|---|---|---|---|
| public | Anyone | Yes | Yes | Methods meant for all users |
| private | Only within defining class | No (implicit receiver only) | No | Internal helper methods |
| protected | Instances of defining class or subclasses | Yes (explicit receiver allowed) | No | Methods shared within family classes |
Key Differences
Public methods are the most open. They can be called from anywhere, on any instance, with an explicit receiver. This is the default visibility for methods in Ruby.
Private methods are more restrictive. They can only be called within the class they are defined in, and you cannot use an explicit receiver when calling them—even self is not allowed. This means private methods are purely internal helpers.
Protected methods are a middle ground. They can be called by any instance of the defining class or its subclasses, but only with an explicit receiver. This allows related objects to share sensitive methods without exposing them publicly.
Code Comparison
Here is an example showing how public methods work in Ruby.
class Person def greet "Hello!" end end person = Person.new puts person.greet
Private and Protected Equivalent
This example shows private and protected methods and how they behave differently.
class Person def call_private private_method end def call_protected(other) other.protected_method end private def private_method "private called" end protected def protected_method "protected called" end end person1 = Person.new person2 = Person.new puts person1.call_private puts person1.call_protected(person2)
When to Use Which
Choose public when you want methods accessible to everyone, like the main actions of your objects. Use private for internal helper methods that should never be called from outside the class, ensuring encapsulation. Opt for protected when you want to allow related objects (instances of the same class or subclasses) to access certain methods, but keep them hidden from the outside world.
Key Takeaways
Public methods are accessible from anywhere with an explicit receiver.Private methods can only be called inside the class without an explicit receiver.Protected methods allow access between instances of the same class or subclasses with an explicit receiver.private for internal helpers, protected for controlled sharing, and public for general API methods.