liveBook · Manning

Method access

As explained in The Well-Grounded Rubyist, Fourth Edition

A method access level is a Ruby visibility classification that controls how a method may be called.

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

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains the three access levels, receiver restrictions, inheritance, and private setter syntax through worked examples.
Examples
Uses Baker’s private helper methods, a protected object comparison, and a private dog-years setter.
What it assumes
Assumes Ruby methods, objects, receivers, self, classes, and inheritance while relating access rules back to self and scope.
What you can do after
Apply public, private, and protected declarations to control interfaces and internal method collaboration.
How it connects
Connects method access to self, scope, receivers, inheritance, private methods, and protected methods.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.