Method_missing in Ruby metaprogramming

Source: Internet
Author: User
We know what the self of the top-level domain is?

 
Puts self # mainputs self. class # object

We know that when a method is called, if no object is accepted, the default value is self, for example:

 
Def tell_me_who puts selfendtell_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

 
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:

 
Puts self # mainputs self. class # objectdef self. method_missing (name, * Arg) puts "# {name} is not exist! "Endputs ask # ask is not exist!

A case causes a bug:

Def self. method_missing (name, * Arg) 1. Times do puts method_name = Name end puts "# {method_name} is not exist! "Endask # 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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.