How to list all methods for an object in Ruby?

后端 未结 8 1908
北荒
北荒 2020-12-07 08:44

How do I list all the methods that a particular object has access to?

I have a @current_user object, defined in the application controller:



        
8条回答
  •  北海茫月
    2020-12-07 09:27

    Module#instance_methods

    Returns an array containing the names of the public and protected instance methods in the receiver. For a module, these are the public and protected methods; for a class, they are the instance (not singleton) methods. With no argument, or with an argument that is false, the instance methods in mod are returned, otherwise the methods in mod and mod’s superclasses are returned.

    module A
      def method1()  end
    end
    class B
      def method2()  end
    end
    class C < B
      def method3()  end
    end
    
    A.instance_methods                #=> [:method1]
    B.instance_methods(false)         #=> [:method2]
    C.instance_methods(false)         #=> [:method3]
    C.instance_methods(true).length   #=> 43
    

提交回复
热议问题