For instance, in Python, I can do things like this if I want to get all attributes on an object:
>>> import sys
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__package__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'gettrace', 'hexversion', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'py3kwarning', 'pydebug', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions']
Or if I want to view the documentation of something, I can use the help function:
>>> help(str)
Is there any way to do similar things in Ruby?
There's a module called
ObjectSpace
which is included into each object created in ruby. It holds all of the methods that help you introspect current context of the process. In irb you begin inObject:Main
context which is top level context for current irb session. Then you could do something liketime = Time.now
and then doirb time
which would take you into that object's context and you could inspect it from the inside without callingObjectSpace
methods on that object.If you want all the methods that you can call on something than use
If you want some help information then call help before its class
Help is a wrapper for ri within irb.
If you have an object, and you want to know what methods it responds to, you can run
obj.methods
(and all of the tricks that thenduks has mentioned on this result.)If you have a class, you can run
klass.methods
to see what class methods are availabe, or you can runklass.instance_methods
to know what methods are available on instances of that class.klass.instance_methods(false)
is useful, becuase it tells you what methods were defined by the class and not inherited.There's now way to get help text for a method within Ruby the way python does.
Sure, it's even simpler than in Python. Depending on what information you're looking for, try:
and if you want just the methods defined for obj (as opposed to getting methods on
Object
as well)Also interesting is doing stuff like:
To get instance variables, do this:
and for class variables: