Ruby:如何在没有对象的情况下获得类的方法?

时间:2022-06-01 21:00:25

"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()…

“abc”.respond_to?(:sub)返回true,但String.respond_to?(:sub)返回false。第二个返回false,因为它询问类的对象是否有方法子对象,因为字符串是类的对象。方法()也是如此。

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

我如何在不创建该类的对象的情况下做这些事情和特殊的respond_to?()。

2 个解决方案

#1


2  

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.method_defined?子都可以发挥作用。如果您对实例方法特别感兴趣,请使用以下内容:

String.instance_methods.index 'sub'

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

注意,您必须使用字符串,而不是符号。

#2


5  

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

您可以使用method_defined吗?方法,在模块类中声明。

#1


2  

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.method_defined?子都可以发挥作用。如果您对实例方法特别感兴趣,请使用以下内容:

String.instance_methods.index 'sub'

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

注意,您必须使用字符串,而不是符号。

#2


5  

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

您可以使用method_defined吗?方法,在模块类中声明。