[英]How to list all the methods defined in top self Object in Ruby?
在Ruby中,我們有簡單的方法來獲取所有局部變量,使用local_variables
和global_variables
方法的全局變量。
我們可以用Object.constants列出常量
但是,有沒有一種內置的方法來列出所有Object方法?
像這樣:
def foo() end
def bar() end
def baz() end
# As `Array.new.methods' or `Array.instance_methods` returns all the methods of an Array object...
# Code to return all the methods defined above # => [:foo, :bar, :baz]
在IRB中,我可以這樣寫:
def foo() end
p [self.methods.include?(:foo), self.respond_to?(:foo)]
在IRB中,輸出為[true, true]
,但在文件中,對標准輸出的輸出為[false, false]
同樣,如果我運行以下代碼:
def foo() end
puts Object.new.methods.include?(:foo)
在IRB中,我為true
,如果將其保存在文件中,則為false
這是一個沒有太大幫助的鏈接 :
僅僅因為它談到獲取類或模塊的方法。 但我想列出在頂部self對象中定義的方法。
我能找到的最接近的方法是在main
對象上調用private_methods
,將false
作為參數
返回obj可訪問的私有方法的列表。 如果all參數設置為false,則僅列出接收者中的那些方法。
def foo
"foo"
end
def bar
"bar"
end
def baz
"baz"
end
p private_methods(false)
# [:include, :using, :public, :private, :define_method, :DelegateClass, :foo, :bar, :baz]
如果省略該參數,則還將獲得在Kernel
或BasicObject
定義的所有私有方法。
為了進一步優化列表,您可以選擇為Object
定義的方法:
p private_methods(false).select{|m| method(m).owner == Object}
#=> [:DelegateClass, :foo, :bar, :baz]
僅保留:DelegateClass
,因為它是在頂級范圍中定義的,就像:foo
, :bar
和:baz
。
你得到false
,因為在頂級背景下定義的方法是通過默認專用。
def foo; end
p self.private_methods.include?(:foo)
# => true
我不確定這是否記錄在任何地方。
為了獲得包括私有方法在內的所有方法,您需要執行以下操作:
all_methods = self.methods | self.private_methods
在repl.it上嘗試: https ://repl.it/@jrunning/DutifulPolishedCell
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.