zoukankan      html  css  js  c++  java
  • 关于ruby的methods、instance_methods、method三者的区别

    class A
        def self.ask1
            puts "the method of class"
        end
        def ask2
            puts "the method of instance"
        end
    end
    

    #类的实例对象的方法,方法属于类所生成New出来的实例对象。
    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
    输出:50

    说明上面5种方式都是输出实例对象的方法


    #增加a实例的单件方法

    def a.tell
    
    end
    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
    

     输出:51 50 51 50
    说明:类的instance_methods包括的只有他所拥有的实例方法,并不包含单件类的方法。并且methods方法其实和Public_methods一样的,有别于private_methods


    #类的方法,方法属于类自己
    p A.methods.length
    p A.class.instance_methods.length
    p A.public_methods.length
    p A.class.public_instance_methods.length

    输出:87 86 87 86

    注:这里根据版本不同,1.8.6和1.9.2是有差别的。


    现在说一下,method方法

    这个方法属于Method类,最常用的就是检查方法的参数个数,如下:

    class A
        def self.ask1(n1,n2)
            puts "the method of class"
        end
        def ask2(n1)
            puts "the method of instance"
        end
    end
    
    a=A.new
    p a.method(:ask2).arity
    p A.method(:ask1).arity
    

     输出:1 2

    这里不拘泥于所有方法的介绍,介绍的是比较常用的方法。

  • 相关阅读:
    Leetcode 589. N-ary Tree Preorder Traversal
    Leetcode 912. Sort an Array
    Leetcode 1020. Number of Enclaves
    Leetcode 496. Next Greater Element I
    Leetcode 1019. Next Greater Node In Linked List
    Leetcode 503. Next Greater Element II
    Leetcode 1018. Binary Prefix Divisible By 5
    龟兔赛跑算法详解
    Leetcode 142. Linked List Cycle II
    Leetcode 141. Linked List Cycle
  • 原文地址:https://www.cnblogs.com/IAmBetter/p/2963688.html
Copyright © 2011-2022 走看看