We know the top-level domain, what is the self of the domain defined?
Copy Code code as follows:
Puts self #main
Puts Self.class #Object
We know that when a method is invoked, if there is no object to accept, the default is self, such as:
Copy Code code as follows:
def tell_me_who
Puts self
End
Tell_me_who #main
A method call is a step to find out whether an instance method of the current object's class exists or not, and if so, call the method, and if it does not exist, view superclass until Basicobject finds the method, and the kernel method_ is invoked. Missing () method, and an error, such as
Copy Code code as follows:
Error:test.rb:8: undefine:undefined local variable or method "Ask" for Main:object (Nameerror)
Pay attention to the error information, we can find that when we call a nonexistent variable, it will be traced back to the kernel method_missing method, here to note slightly.
Verify:
Copy Code code as follows:
Puts self #main
Puts Self.class #Object
def self.method_missing (Name,*arg)
Puts "#{name} is not exist!"
End
Puts ask #ask isn't exist!
One case causes a bug:
Copy Code code as follows:
def self.method_missing (Name,*arg)
1.times do
Puts Method_name=name
End
Puts "#{method_name} is not exist!"
End
Ask #变量或者方法
Intent: Make any undefined variable or method print once
But is this a dead loop? You see the problem?
Ask is executed, but without the definition ask, it will go to method_missing,
Method_name in the block of times, out of scope, so will execute the method_missing, into a dead loop.