checking if a method is defined on the class

后端 未结 3 1453
有刺的猬
有刺的猬 2021-02-01 03:30

How do I check if a method is defined on some class directly, not by inheritance or by inclusion/extension? I want something like \'foo?\' in the following:

clas         


        
3条回答
  •  北海茫月
    2021-02-01 03:49

    Use this:

    C.instance_methods(false).include?(:a)
    C.instance_methods(false).include?(:b)
    C.instance_methods(false).include?(:c)
    

    The method instance_methods return an Array of methods that an instance of this class would have. Passing false as first parameter returns only methods of this class, not methods of super classes.

    So C.instance_methods(false) returns the list of methods defined by C.

    Then you just have to check if that method is in the returned Array (this is what the include? calls do).

    See docs

提交回复
热议问题