Instance methods are defined inside a class definition block. Class methods are defined as singleton methods on the singleton class of a class, also informally known as the "metaclass" or "eigenclass". private
is not a keyword, but a method (Module#private).
This is a call to method self#private
/A#private
which "toggles" private access on for all forthcoming instance method definitions until toggled otherwise:
class A
private
def instance_method_1; end
def instance_method_2; end
# .. and so forth
end
As noted earlier, class methods are really singleton methods defined on the singleton class.
def A.class_method; end
Or using a special syntax to open the definition body of the anonymous, singleton class of A:
class << A
def class_method; end
end
The receiver of the "message private" - self - inside class A
is the class object A. self inside the class << A
block is another object, the singleton class.
The following example is in reality calling two different methods called private, using two different recipients or targets for the call. In the first part, we define a private instance method ("on class A"), in the latter we define a private class method (is in fact a singleton method on the singleton class object of A).
class A
# self is A and private call "A.private()"
private def instance_method; end
class << self
# self is A's singleton class and private call "A.singleton_class.private()"
private def class_method; end
end
end
Now, rewrite this example a bit:
class A
private
def self.class_method; end
end
Can you see the mistake [that Ruby language designers] made? You toggle on private access for all forthcoming instance methods of A, but proceed to declare a singleton method on a different class, the singleton class.