I have a module Commands
with several static methods defined ( self.method
). I want to get a list of methods in Commands
, but instance_methods
and similar methods seem to recognize only non-static methods, since the return of Commands.instance_methods
is empty.
The code is as follows:
module Commands
def self.method_1
end
def self.method_N
end
end
Commands.instance_methods
is empty ( []
).
You can use Commands.singleton_methods
in this case.
It will return array of method names.
When you define methods within a module or class definition using this syntax
def self.foo
'foo'
end
you are defining a class method, not an instance method. So calling Commands.instance_methods
will return empty array unless any have been defined.
To get methods defined on the class but exclude inherited methods, use:
Commands.methods(fasle)
If you don't pass false
or nil
you will get all instance methods including those which have been inherited.
Now if you want to get all 3 types in one shot, you could do something like:
[:methods, :instance_methods, :singleton_methods].map{|m| Commands.send(m, false)}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.