Method access controls when a Ruby method may be called. Its rules depend on the calling context, especially self: public, private, and protected methods each impose different restrictions. section 5.0 section 5.5
Ruby provides three access levels:
- Public methods form the ordinary callable interface. section 5.5
- Private methods support internal work and cannot normally be called with an explicit receiver. A class can mark methods private with declarations such as private or private :method_name. section 5.3.1
- Protected methods resemble private methods, but permit calls between objects whose classes are the same or related through inheritance. section 5.3.2
A protected comparison
class C def initialize(n) @n = n end def n @n end def compare(c) if c.n > n puts "The other object's n is bigger." else puts "The other object's n is the same or smaller." end end protected :n end c1 = C.new(100) c2 = C.new(101) c1.compare(c2) Inside compare, c1 asks c2 to execute n. That call would fail if n were private, but succeeds because both objects are instances of C. section 5.3.2
Access rules are inherited. A subclass keeps its superclass’s method-access behavior unless its own class definition establishes a new rule that takes precedence. section 5.3.2
Private setter methods are an edge case: self may explicitly receive a private setter call, as in self.dog_years = years, because omitting self would look like local-variable assignment. section 5.3.1
