Method Visibility & Access Modifiers
Master Ruby's access modifiers: public, private, and protected methods with practical examples and best practices.
🚀 Interactive Practice
Interactive Code Runner
Ruby Code Editor
🎯 Key Takeaways
- public: Default visibility, accessible from anywhere
- private: Only callable within the same object
- protected: Accessible by same class and subclasses
- Encapsulation: Hide internal implementation details
Method Visibility & Access Modifiers
Method visibility controls how methods can be accessed in Ruby. Understanding public, private, and protected methods is essential for proper object-oriented design and encapsulation.
Understanding Method Visibility
Method Visibility: Controls who can call a method. Ruby has three levels: public (default), private, and protected.
Basic Example
- Public: Can be called from anywhere (default)
- Private: Can only be called from within the same object
- Protected: Can be called from the same class or subclasses
Public Methods
Public Methods: The default visibility. Can be called from anywhere - outside the class, from subclasses, or from within the class itself.
Public Method Examples
Key Points:
- Public is the default visibility for all methods
- Can be called from anywhere - outside the class, subclasses, or within the class
- Use
publickeyword to explicitly declare (optional) - Most interface methods should be public
Private Methods
Private Methods: Can only be called from within the same object. Cannot be called with an explicit receiver (no dot notation from outside).
Private Method Examples
Key Points:
- Cannot be called with explicit receiver (no
object.private_method) - Can only be called from within the same object
- Use for internal implementation details and helper methods
- All methods after
privatekeyword become private
Protected Methods
Protected Methods: Can be called from the same class or its subclasses. Cannot be called from outside the class hierarchy.
Protected Method Examples
Key Points:
- Can be called from the same class or its subclasses
- Cannot be called from outside the class hierarchy
- Useful for methods that subclasses need but shouldn't be public
- Less commonly used than public and private
Advanced Visibility Patterns
Advanced Patterns: Ruby provides flexible ways to control method visibility including selective visibility changes, module inclusion, and dynamic visibility control.