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”, “removesubclassesof”, “`”, “type”, “debugger”, “blank?”, “instanceeval”, “protectedmethods”, “display”, “==”, “silencestream”, “unloadable”, “decode64”, “===”, “actslike?”, “pm”, “c”, “toyamlstyle”, “instancevariableset”, “extend”, “kindof?”, “tos”, “extendedby”, “class”, “hash”, “breakpoint”, “present?”, “mocha”, “privatemethods”, “=~”, “tainted?”, “decodeb”, “mochainspect”, “instancevalues”, “untaint”, “nil?”, “loadwithnewconstantmarking”, “is_a”, “bar”, “stubbaobject”, “prettyprintinspect”, “requiredependency”, “isa?”, “prettyprintinstancevariables”, “metaclass”] “`

See the difference? Call it micro-documentation.

☙ ☙ ☙