给定任何对象,我都可以调用#public_methods并查看它将响应的所有方法.然而,我发现有时可以方便地快速列出所有未被继承的公共方法,即真正属于此类的内容.

我在"Easy way to list public methods for a Ruby object"中发现,如果我使用:

(Foo.public_methods - Object.public_methods).sort

我可以过滤掉很多基本的Ruby元素.我希望能够过滤整个链条中继承的所有内容.如果我知道父类,我可以使用它进行过滤,但我想提出一个通用命令,它可以为任何对象返回一个未继承的公共方法array.

推荐答案

对于public_methodsinherited参数,只需通过false:

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

不是你问题的答案,但如果你不知道,irb会自动完成,所以很容易获得公共方法列表(特别是如果你知道你要寻找的方法的开头).点击tab;点击两次将列出所有可能性(包括继承的可能性):

> "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_

Ruby相关问答推荐

Ruby vs Scala - 各自的优缺点

如何使 Sinatra 通过 HTTPS/SSL 工作?

带有索引的 Ruby `each_with_object`

Ruby 中的字符串是可变的吗?

Ruby 中的 :+ 和 &:+ 是什么?

可可豆荚安装在iOS项目上不起​​作用

如何判断是否安装了gem?

扩展self 和module_function一样吗?

我可以在 Ruby 2.x 中要求命名参数吗?

如何在 ruby​​ net/http 中实现 cookie 支持?

条件子句中的赋值是好的Ruby风格吗?

获取类中声明的所有实例变量

如何在Ruby中获取给定月份的天数,占年份?

在 Ruby 中打开默认浏览器

获取Ruby中当前目录的父目录

如何在 macOS 上卸载 rbenv?

当我们导入 csv 数据时,如何消除UTF-8 中的无效字节序列

如何在不为 RVM 用户授予 sudo 访问权限的情况下安装 RVM 系统要求

Eclipse 的首选 Ruby 插件?

如何在遍历数组时使用 Array#delete?