Easy way to list public methods for a Ruby object

March 25, 2009 by alex

I often have new code I'm trying to figure out, and constantly jumping back and forth between a console and a web browser with documentation sometimes really slows me down. Often times it's easy enough to remember which method you want just by seeing a list, even without detailed descriptions.

Any object has a rubypublic_methods method, which returns an array of strings listing the commands. Trouble is, all the methods it inherits are of course listed in there, and rubyObject provides a LOT of stuff. It's easy for the interesting stuff about the instance at hand to get lost in that noise.

So, I'm trying a little experiment. I added this snippet to my ~/.irbrc file. Works on Linux and OSX, and in either normal irb or in the Rails console. ruby class Object # print public methods which are not inherited from Object def pm (self.public_methods - Object.public_methods).sort end end Now any object has a rubypm method. So what?

```ruby Loading development environment (Rails 2.2.2) >> class Blah >> def foo; end >> def bar; end >> def blatz; end >> end => nil >> b = Blah.new => #

b.pm => ["bar", "blatz", "foo"] >> b.publicmethods => ["returning", "toyaml", "prettyprintcycle", "inspect", "methodexists?", "stubs", "toparam", "extendwithincludedmodulesfrom", "subclassesof", "requireorload", "clone", "method", "toenum", "toyamlproperties", "publicmethods", "metaclass", "tojson", "suppress", "instancevariabledefined?", "instancevariablenames", "dclone", "equal?", "blatz", "freeze", "expects", "withoptions", "foo", "methods", "respondto?", "geometrydatatypes", "instanceexec", "enablewarnings", "tomatcher", "toquery", "silencewarnings", "resetmocha", "toc", "dup", "enumfor", "instancevariables", "id", "copyinstancevariablesfrom", "duplicable?", "eql?", "objectid", "prettyinspect", "require", "id", "send", "singletonmethods", "silencestderr", "encode64", "classeval", "taint", "taguri", "requireassociation", "stubbamethod", "instancevariableget", "frozen?", "instanceof?", "send", "requirelibraryorgem", "b64encode", "toa", "prettyprint", "taguri=", "daemonize", "removesubclasses_of", "", "type", "debugger", "blank?", "instance_eval", "protected_methods", "display", "==", "silence_stream", "unloadable", "decode64", "===", "acts_like?", "pm", "c", "to_yaml_style", "instance_variable_set", "extend", "kind_of?", "to_s", "extended_by", "class", "hash", "breakpoint", "present?", "mocha", "private_methods", "=~", "tainted?", "decode_b", "mocha_inspect", "instance_values", "untaint", "nil?", "load_with_new_constant_marking", "__is_a__", "bar", "stubba_object", "pretty_print_inspect", "require_dependency", "is_a?", "pretty_print_instance_variables", "metaclass"] ``

See the difference? Call it micro-documentation.

☙ ☙ ☙