How to Use Protected Method in Ruby: Syntax and Examples
protected method is defined inside a class using the protected keyword. It can be called by any instance of the defining class or its subclasses, but not from outside objects. Use protected to allow controlled access between related objects.Syntax
To define a protected method in Ruby, place the protected keyword before the method definitions. All methods defined after this keyword will be protected until another visibility keyword (public or private) is used.
Protected methods can be called by any instance of the same class or its subclasses, but not from outside objects.
class MyClass protected def protected_method puts "This is a protected method" end end
Example
This example shows how two instances of the same class can call each other's protected method, but an outside object cannot.
class Person def initialize(name) @name = name end protected def secret "Secret of #{@name}" end public def reveal_secret(other_person) other_person.secret end end alice = Person.new("Alice") bob = Person.new("Bob") puts alice.reveal_secret(bob) # Alice can access Bob's protected method # The following line would cause an error if uncommented: # puts bob.secret # Cannot call protected method from outside
Common Pitfalls
One common mistake is trying to call a protected method directly from outside the class, which raises a NoMethodError. Another is confusing protected with private: private methods cannot be called with an explicit receiver, even if it is the same class instance.
Protected methods allow calls between instances of the same class, but private methods do not.
class Example protected def prot "protected" end private def priv "private" end end obj1 = Example.new obj2 = Example.new # Correct: calling protected method on another instance puts obj1.send(:prot) # works because send bypasses visibility # puts obj1.prot # Error if called directly outside class # Incorrect: calling private method on another instance # puts obj1.priv # Error: private method called with explicit receiver # Correct: calling private method inside class without receiver class Example def call_priv priv end end puts obj1.call_priv # works
Quick Reference
| Keyword | Access Level | Callable By | Example Usage |
|---|---|---|---|
| public | Any object | Anywhere | def method_name; end |
| protected | Same class and subclasses | Instances of same class or subclass | protected def method_name; end |
| private | Same class only | Only within same instance, no explicit receiver | private def method_name; end |
Key Takeaways
protected to allow method calls between instances of the same class or subclasses.protected before method definitions.NoMethodError.