本文介绍了为什么 Module.method_defined?(:method) 不能正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Module.method_defined?(:method) 检查模块中是否定义了一个方法,它返回 false,它应该返回 true.

I'm trying to check if a method is defined in a module using Module.method_defined?(:method) and it is returning false it should be returing true.

module Something
  def self.another
    1
  end
end

Something.methods 列出了another",但 Something.method_defined?(:another) 返回 false.

Something.methods has 'another' listed but Something.method_defined?(:another) returns false.

这是否可能不起作用,因为该方法是在 self 上定义的?如果是这种情况,除了使用 method_defined??

Is this maybe not working because the method is defined on self? If this is the case is there another way to check if the method is defined on the module other than using method_defined??

推荐答案

要知道模块是否有模块方法,可以使用respond_to?在模块:

To know whether the module has a module method, you can use respond_to? on themodule:

Something.respond_to?(another)
=> true

method_defined?会告诉你包含模块的类的实例是否响应给定的方法.

method_defined? will tell you whether INSTANCES of the class with the module included responds to the given method.

这篇关于为什么 Module.method_defined?(:method) 不能正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 05:19