Differences between Ruby's methods, instance_methods, and Method

Source: Internet
Author: User
Class A def self. ask1 puts "the method of Class" End def ask2 puts "the method of instance" endend

# Method of the Instance Object of the class. The method belongs to the new instance object generated by the class.
P a. Methods. Length
P a. Class. instance_methods.length
P a. instance_methods.length
P a. public_methods.length
P a. Class. public_instance_methods.length
Output: 50

The preceding five methods are used to output instance objects.

# Add a single-piece Method for instance

 
Def A. tellendp A. Methods. lengthp A. Class. instance_methods.lengthp A. Category A. public_methods.lengthp A. Class. public_instance_methods.length

Output: 51 50 51 50
Note: The instance_methods of a class includes only the instance methods it owns, and does not include the methods of a single class. In addition, the methods method is actually the same as public_methods, which is different from private_methods.

# Class method, which belongs to the class itself
P a. Methods. Length
P a. Class. instance_methods.length
P a. public_methods.length
P a. Class. public_instance_methods.length

Output: 87 86 87 86

Note: 1.8.6 and 1.9.2 are different based on different versions.

Now let's talk about the method.

This method belongs to the method class. The most common method is to check the number of parameters of the method, as shown below:

 
Class A def self. ask1 (N1, N2) puts "the method of Class" End def ask2 (N1) puts "the method of instance" endenda =. newp. method (: ask2 ). arityp. method (: ask1 ). arity

Output: 1 2

Here we will not stick to the introduction of all the methods, but will introduce the more common methods.

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.