• 关于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

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

  • 相关阅读:
    .NET Core自定义TagHelper和使用Serilog
    .NET Core CSRF
    jq 获取表单全部数据
    Webuploader 简单图片上传 支持多图上传
    CF-1451 E Bitwise Queries 异或 交互题
    CF-1440C2 Binary Table (Hard Version) (构造,模拟)
    CF-1445 C
    ACM模板_axiomofchoice_extra
    Codeforces Round #678 (Div. 2) 题解 (A-E)
    Oracle数据同步
  • 原文地址:https://www.cnblogs.com/IAmBetter/p/2963688.html
Copyright © 2020-2023  润新知