Ruby: How to get methods of a class without its object?

"abc" .respond_to? (: sub) returns true, but String.respond_to? (: sub) returns false. The second returns false because it asks if objects of class Class have a sub method since String is a class object. Ditto for methods () ...

How can I do these things and especially respond to_ (?) Without creating an object of that class.

+2


source to share


2 answers


If you are trying to confirm if a method exists String.method_defined? :sub

will work. If you are especially interested in instance methods, use something like:

String.instance_methods.index 'sub'

      



Please note that you must use a string, not a character.

+2


source


You can use the method method_defined?

declared in the class Module

.



+5


source







All Articles