johannes
johannes

Reputation: 7272

Ruby: How do I get the methods of a class without having an object of it?

"abc".respond_to?(:sub) returns true, but String.respond_to?(:sub) returns false. The second returns false, because it asks whether objects of the class Class have a method sub, as String is an Object of Class. It is the same for methods()…

How do I do these things and especialy respond_to?() without creating an Object of that class.

Upvotes: 2

Views: 235

Answers (2)

Pesto
Pesto

Reputation: 23880

If you are trying to confirm whether a method exists, String.method_defined? :sub will work. If you are specifically interested in instance methods, use something like:

String.instance_methods.index 'sub'

Note that you have to use a string, not a symbol.

Upvotes: 2

samuil
samuil

Reputation: 5081

You can use method_defined? method, declared in Module class.

Upvotes: 5

Related Questions