list classes and methods in a ruby module

February 12, 2010

in linux,software

Here’s a simple script to list the classes and class instance methods within in a particular module. I’ve been experimenting with using SWIG (more on that in an upcoming post), and wanted to quickly check, from the ruby end, what classes and methods were generated. If you’ve created ruby extensions before, you know that the C code creating the ruby classes isn’t as well organized as the resulting ruby classes themselves, and the hypothetical corresponding ruby code. This little one-liner let me quickly see what was generated in an organized way. What’s nice is when working on huge extensions, I can pipe this to grep straight from the command line to see if a certain class / function was created. Anyways, here it is (In this example, I’m using the module “set” to demonstrate, just replace the require and the module name in lines 1 and 2 of the script to what you want to inspect):

1
2
3
require 'set'
mod = Set
mod.constants.collect{|c| mod.const_get(c)}.select{|c| c.class == Class}.each{|c| puts c.to_s; c.instance_methods(false).each{|m| puts ' ' + c.instance_method(m).to_s}}

if you ran this, this is the output you’d see:

Enumerable::Enumerator
 #<UnboundMethod: Enumerable::Enumerator#next>
 #<UnboundMethod: Enumerable::Enumerator#each_with_index>
 #<UnboundMethod: Enumerable::Enumerator#with_index>
 #<UnboundMethod: Enumerable::Enumerator#rewind>
 #<UnboundMethod: Enumerable::Enumerator#each>

Cheers!

Leave a Comment

Previous post:

Next post: