Ruby相当于Python的"dir"?

50 ruby python inspection

在Python中,我们可以"dir"一个模块,如下所示:

>>> import re
>>> dir(re)
Run Code Online (Sandbox Code Playgroud)

它列出了模块中的所有功能.在Ruby中有类似的方法吗?

Jon*_*röm 54

据我所知不完全,但你得到的地方

object.methods.sort
Run Code Online (Sandbox Code Playgroud)


Com*_*een 20

我喜欢在我的.irbrc中有这个:

class Object
  def local_methods
    (methods - Object.instance_methods).sort
  end
end
Run Code Online (Sandbox Code Playgroud)

所以当我在irb时:

>> Time.now.local_methods 
=> ["+", "-", "<", "<=", "<=>", ">", ">=", "_dump", "asctime", "between?", "ctime", "day", "dst?", "getgm", "getlocal", "getutc", "gmt?", "gmt_offset", "gmtime", "gmtoff", "hour", "isdst", "localtime", "mday", "min", "mon", "month", "sec", "strftime", "succ", "to_f", "to_i", "tv_sec", "tv_usec", "usec", "utc", "utc?", "utc_offset", "wday", "yday", "year", "zone"]
Run Code Online (Sandbox Code Playgroud)

甚至可爱 - 用grep:

>> Time.now.local_methods.grep /str/
=> ["strftime"]
Run Code Online (Sandbox Code Playgroud)


met*_*hod 5

在 irb 中“搜索”方法的提示:

"something".methods.select {|item| item =~ /query/ }
Run Code Online (Sandbox Code Playgroud)

尝试对值进行比较的方法的提示:

value = "something"
[:upcase, :downcase, :capitalize].collect {|method| [method, value.send(method)] }
Run Code Online (Sandbox Code Playgroud)

另请注意,您不会通过 object.methods 获得与 Python 目录相同的信息。您必须使用 object.methods 和 class.constants 的组合,以及 class.singleton_methods 来获取类方法。