我正在尝试检查一个方法是否在一个模块中使用Module.method_defined?(:method)并且它返回false它应该返回true.
module Something
def self.another
1
end
end
Run Code Online (Sandbox Code Playgroud)
Something.methods有'另一个'列出但Something.method_defined?(:another)返回false.
这可能不起作用,因为该方法是在自我定义的吗?如果是这种情况,还有另一种方法可以检查方法是否在模块上定义而不是使用method_defined??
enn*_*ler 12
要知道模块是否具有模块方法,您可以使用respond_to?在模块上:
Something.respond_to?(another)
=> true
Run Code Online (Sandbox Code Playgroud)
method_defined?将告诉您包含模块的类的INSTANCES是否响应给定的方法.
模块方法在其元类中定义.因此,您还可以检查方法包含:
k = class << Something; self; end # Retrieves the metaclass
k.method_defined?(:another) #=> true
Run Code Online (Sandbox Code Playgroud)
您可以在了解Ruby Metaclasses中阅读更多相关信息.
| 归档时间: |
|
| 查看次数: |
4901 次 |
| 最近记录: |