![](/img/trans.png)
[英]Ruby: How do I get the methods of a class without having an object of it?
[英]How do I get the public methods of a class without inherited methods?
給定任何對象我可以調用#public_methods
並查看它將響應的所有方法。 但是,我發現有時候獲得一個沒有繼承的所有公共方法的快速列表是有用的,也就是那些真正屬於這個類的東西。
我找到了“ 簡單的方法列出Ruby對象的公共方法 ”,如果我使用:
(Foo.public_methods - Object.public_methods).sort
我可以過濾掉很多基本的Ruby東西。 我希望能夠過濾掉鏈條上一直延續的所有內容。 如果我知道父類我可以使用它進行過濾,但我想提出一個通用命令,它可以返回任何對象的未公開公共方法的數組。
只是為public_methods
的inherited
參數傳遞false
:
"hello".public_methods.include?(:dup) # => true
"hello".public_methods(false).include?(:dup) # => false
不是你的問題的答案,但如果你不知道, irb
會自動完成,所以很容易獲得公共方法列表(特別是如果你知道你正在尋找的方法的開頭)。 只需點擊標簽; 兩次擊中將列出所有可能性(包括繼承的可能性):
> "nice".d<tab><tab>
"nice".delete "nice".delete! "nice".display "nice".downcase
"nice".downcase! "nice".dump "nice".dup "nice".define_singleton_method
> "nice".<tab><tab>
Display all 162 possibilities? (y or n)
...
使用pry
可以更容易地看到可用的方法,按繼承級別細分:
[1] pry(main)> cd "nice"
[2] pry("nice"):1> ls
Comparable#methods: < <= > >= between?
String#methods: % * + << <=> == === =~ [] []= ascii_only? bytes bytesize byteslice capitalize capitalize! casecmp center chars chomp chomp! chop chop! chr clear codepoints concat count crypt delete delete! downcase downcase! dump each_byte each_char each_codepoint each_line empty? encode encode! encoding end_with? eql? force_encoding getbyte gsub gsub! hash hex include? index insert inspect intern length lines ljust lstrip lstrip! match next next! oct ord partition prepend replace reverse reverse! rindex rjust rpartition rstrip rstrip! scan setbyte shellescape shellsplit size slice slice! split squeeze squeeze! start_with? strip strip! sub sub! succ succ! sum swapcase swapcase! to_c to_f to_i to_r to_s to_str to_sym tr tr! tr_s tr_s! unpack upcase upcase! upto valid_encoding?
locals: _ _dir_ _ex_ _file_ _in_ _out_ _pry_
看看Module#instance_methods 。 該方法有一個布爾參數include_super
是否也返回繼承的方法。 默認值為true。
您可以使用以下內容:
class A
def method_1
puts "method from A"
end
end
class B < A
def method_2
puts "method from B"
end
end
B.instance_methods # => [:method_1, :method_2, ...]
B.instance_methods(false) # => [:method_2]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.