繁体   English   中英

Ruby:获取静态方法列表

[英]Ruby: get a list of static methods

我有一个模块Commands ,其中定义了几个静态方法( self.method )。 我想获取Commands中的方法列表,但instance_methods和类似方法似乎只能识别非静态方法,因为Commands.instance_methods的返回值为空。

代码如下:

module Commands
  def self.method_1
  end

  def self.method_N
  end
end

Commands.instance_methods为空 ( [] )。

在这种情况下,您可以使用Commands.singleton_methods

它将返回方法名称数组。

当您使用此语法在模块或类定义中定义方法时

def self.foo
  'foo'
end

您正在定义一个类方法,而不是一个实例方法。 因此调用Commands.instance_methods将返回空数组,除非已定义任何数组。

要获取在类上定义的方法但排除继承的方法,请使用:

Commands.methods(fasle)

如果您不传递falsenil您将获得所有实例方法,包括那些已被继承的方法。

现在,如果您想一次获得所有 3 种类型,您可以执行以下操作:

[:methods, :instance_methods, :singleton_methods].map{|m| Commands.send(m, false)}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM