Ruby equivalent of Python's “dir”?

2020-02-17 04:16发布

In Python we can "dir" a module, like this:

>>> import re
>>> dir(re)

And it lists all functions in the module. Is there a similar way to do this in Ruby?

9条回答
Bombasti
2楼-- · 2020-02-17 04:39

I'd go for something like this:

y String.methods.sort

Which will give you a yaml representation of the sorted array of methods. Note that this can be used to list the methods of both classes and objects.

查看更多
3楼-- · 2020-02-17 04:42

I would have made this a comment to jonelf's answer, but apparently I don't have enough rep.

some_object.methods.sort - Object.new.methods

This isn't exactly what you were asking as others have said, but it gives you the info you are after.

查看更多
We Are One
4楼-- · 2020-02-17 04:45

I like to have this in my .irbrc:

class Object
  def local_methods
    (methods - Object.instance_methods).sort
  end
end

So when I'm in 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"]

Or even cuter - with grep:

>> Time.now.local_methods.grep /str/
=> ["strftime"]
查看更多
手持菜刀,她持情操
5楼-- · 2020-02-17 04:49

As far as I know not exactly but you get somewhere with

object.methods.sort
查看更多
【Aperson】
6楼-- · 2020-02-17 04:50

Not really. Like the others said, you can get part of what you want by listing class instance methods (e.g. String.instance_methods) but that doesn't help you if a file you open reopens a class (unless you check before and after).

If you don't need programmatic access to the list of methods, consider checking out the documentation for a class, module or method using the ri command line tool.

查看更多
啃猪蹄的小仙女
7楼-- · 2020-02-17 04:55

Tip for "searching" for a method in irb:

"something".methods.select {|item| item =~ /query/ }

Tip for trying out methods on a value for comparison:

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

Also, note that you won't get all the same information as Python's dir with object.methods. You have to use a combination of object.methods and class.constants, also class.singleton_methods to get the class methods.

查看更多
登录 后发表回答