When writing top-level functions in ruby, there will always be a problem: Who is self, who is the method, and what is the method.
As follows:
1 p self
2
3 p self.class
4
5 def talk
6 p self
7 end
8
9 talk
Output main, object, main
It can be seen that when writing top-level code, Ruby automatically provides a default self, which is an instance object of the object class, Main.
So who does this talk belong? Although its current self is main.
Pass special rules (that is, prescribed. Refer to Ruby for rails on the 153 page). The top-level method is the private instance method of the object class.
Private instance, which means that the call cannot be displayed. The class of each object is the descendant of the object. Therefore, each object can call the top-level method, but it cannot display the call.
As follows:
1 def talk
2 puts "hello world"
3 end
4 talk
5
6 obj = Object.new
7
8
9 def obj.method
10 talk
11 end
12 obj.method
13
14 obj.talk
The output is Hello world, hello World, in '<main>': Private method 'tal' called for # <object: 0x1ee7768> (nomethoderror)
Defines a top-level method of talk. Main is called as the receiver and is valid. Define the object OBJ of an object, create a singleton Method for OBJ, and call talk in method, which is also valid. This is because in the singleton method, self is OBJ, and obj is an instance of the object. You can call the instance method of the object (the top-level method is a private instance method ). However, you cannot call the talk method directly outside, because talk is a private method. As the error says.
In addition, the top-level methods of puts and print are private instance methods built in the kernel. Therefore, the call cannot be displayed.