One Usage Details of method_missing in ruby metaprogramming, rubymethod_missing

Source: Internet
Author: User

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.

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.