簡體   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