One Usage Details of method_missing in ruby metaprogramming, rubymethod_missing
We know what the self of the top-level domain is?
Copy codeThe Code is as follows:
Puts self # main
Puts self. class # Object
We know that when a method is called, if no object is accepted, the default value is self, for example:
Copy codeThe Code is as follows:
Def tell_me_who
Puts self
End
Tell_me_who # main
Method calling is a step like this. First, check whether the instance method of the current object's class has a method. If so, call the method. If not, view the superclass, until BasicObject does not find the method, it will call the method_missing () method of the Kernel and report an error, as shown in
Copy codeThe Code is as follows:
Error: test. rb: 8: undefine: undefined local variable or method 'Ask 'for main: Object (NameError)
Note the error message. We can find that when we call a non-existent variable, the method_missing method of the Kernel will be traced back.
Verification:
Copy codeThe Code is as follows:
Puts self # main
Puts self. class # Object
Def self. method_missing (name, * arg)
Puts "# {name} is not exist! "
End
Puts ask # ask is not exist!
A case causes a BUG:
Copy codeThe Code is as follows:
Def self. method_missing (name, * arg)
1. times do
Puts method_name = name
End
Puts "# {method_name} is not exist! "
End
Ask # VARIABLES or methods
Intent: print all undefined variables or methods once.
But is this an endless loop? See the problem?
Ask is executed, but the definition of ask is not defined, it will be transferred to method_missing,
Method_name is out of scope in the times block, so method_missing is executed again, which turns into an endless loop.