How do I introspect things in Ruby?

Jason Baker picture Jason Baker · Mar 22, 2010 · Viewed 10.4k times · Source

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?

Answer

rfunduk picture rfunduk · Mar 22, 2010

Sure, it's even simpler than in Python. Depending on what information you're looking for, try:

obj.methods

and if you want just the methods defined for obj (as opposed to getting methods on Object as well)

obj.methods - Object.methods

Also interesting is doing stuff like:

obj.methods.grep /to_/

To get instance variables, do this:

obj.instance_variables

and for class variables:

obj.class_variables