A method_missing of the use of Ruby Meta programming _ruby topics

Source: Internet
Author: User
Tags instance method

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.

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.