Private methods in rubyThis means that a method can only be called implicitly and cannot be called explicitly. When the receiver is not displayed, self is treated as the receiver. Therefore, only private methods can be called in itself, which is also the calling rule of private methods.
Ruby's private method mechanism aims to make it easy to classify methods into two types: accessible methods in the external world and inaccessible methods in the external world.
As follows:
1 class A 2 def a 3 self.method 4 end 5 def method 6 p "hello world" 7 end 8 private :method 9 end10 A.new.a
Method is defined as a private method. It cannot be called directly. It can only be called through method A, but it cannot run normally in method. Because private methods must be called implicitly. Remove self. The default receiver of method is the Instance Object of A, and method is the instance method of.
Differences between private methods and Singleton methods:
The Singleton method is the method of an object. It belongs to this object. By default, it is public. You can also set it to private.
Private non-singleton methods can be shared by any number of objects, but they need to be called from an appropriate occasion. Can they be called as a deciding factor for private methods, it is not about the object to which the message is sent, but about the object self when the message is sent.
Protection Method:
Protection method call rules: as long as the default object self and the object of the method you want to call belong to the same class instance, you can call this protection method.
It is designed to allow instances of a class to collaborate with another instance of the class to complete some tasks.
As follows:
1 class A 2 def initialize(n) 3 @n = n 4 end 5 6 def n 7 @n 8 end 9 10 def compare(c)11 if c.n > n 12 puts "The other object is bigger"13 else14 puts "THe other object is smaller"15 end16 end17 protected :n 18 end19 c1 = A.new(100)20 c2 = A.new(20)21 c1.compare(c2)
This program is used to compare the size of two numbers, both of which are instances of the same class. Therefore, the protected method is valid.
Inheritance and private methods
Subclass inherits the access permission rules of the parent class. If Class C has a set of access permission rules and Class D is a subclass of class C, the instance of class D will show the same access permission rules as the instance of class C. However, if a new access permission rule is defined in Class D, the new rule takes precedence over the inherited rule.