Top-level methods in ruby

Source: Internet
Author: User

When writing top-level functions in ruby, there will always be a problem: Who is self, who is the method, and what is the method.

As follows:

 
1 p self
2 
3 p self.class
4 
5 def talk
6     p self
7 end
8 
9 talk

Output main, object, main

It can be seen that when writing top-level code, Ruby automatically provides a default self, which is an instance object of the object class, Main.

So who does this talk belong? Although its current self is main.

Pass special rules (that is, prescribed. Refer to Ruby for rails on the 153 page). The top-level method is the private instance method of the object class.

Private instance, which means that the call cannot be displayed. The class of each object is the descendant of the object. Therefore, each object can call the top-level method, but it cannot display the call.

As follows:

 
 1 def talk
 2     puts "hello world"
 3 end
 4 talk
 5 
 6 obj = Object.new
 7 
 8 
 9 def obj.method
10     talk
11 end
12 obj.method
13     
14 obj.talk 

The output is Hello world, hello World, in '<main>': Private method 'tal' called for # <object: 0x1ee7768> (nomethoderror)

Defines a top-level method of talk. Main is called as the receiver and is valid. Define the object OBJ of an object, create a singleton Method for OBJ, and call talk in method, which is also valid. This is because in the singleton method, self is OBJ, and obj is an instance of the object. You can call the instance method of the object (the top-level method is a private instance method ). However, you cannot call the talk method directly outside, because talk is a private method. As the error says.

 

In addition, the top-level methods of puts and print are private instance methods built in the kernel. Therefore, the call cannot be displayed.

 

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.