43

任意のオブジェクトを呼び出し#public_methodsて、それが応答するすべてのメソッドを確認できます。ただし、継承されていないすべてのパブリック メソッド、つまりこのクラスの実際の一部であるものの簡単なリストを取得すると便利な場合があります。

「 Rubyオブジェクトのパブリックメソッドを簡単にリストする方法」で、使用すると次のことがわかりました。

(Foo.public_methods - Object.public_methods).sort

多くの基本的な Ruby のものを除外できます。チェーン全体で継承されたすべてのものをフィルタリングできるようにしたいと考えています。親クラスがわかっている場合は、それを使用してフィルター処理できますが、任意のオブジェクトの継承されていないパブリック メソッドの配列を返すことができる汎用コマンドを考えたいと思います。

4

2 に答える 2

72

falseinherited引数を渡すだけです。public_methods

"hello".public_methods.include?(:dup) # => true
"hello".public_methods(false).include?(:dup) # => false

あなたの質問への答えではありませんが、あなたが知らなかった場合、irbオートコンプリートを行うので、パブリックメソッドのリストを簡単に取得できます(特にあなたが探しているメソッドの始まりを知っている場合)。タブを押すだけです。2回押すと、すべての可能性が一覧表示されます(ただし、継承されたものも含まれます)。

> "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_
于 2012-01-13T04:02:15.070 に答える