pm: Print Methods
Thursday, November 9th, 2006Ruby has a very convenient method to inspect objects: “p”. It just prints the result of “inspect”. And it’s exactly what irb uses to show the result of each expression.
Anyway, the cool guys at projectionist just posted a little method of theirs called “m”, which provides easy access to an object’s methods.
That made me remember my old (well, not that old) “pm” method for irb, which even if I haven’t talked about here, I’ve made public at dotfiles as part of my irbirc (it’s the last method).
Anyway, looking at their implementation, I decided to polish mine and release it here:
ANSI_RESET = " 33[0m"
ANSI_BOLD = " 33[1m"
ANSI_GRAY = " 33[1;30m"
ANSI_LGRAY = " 33[0;37m"
def pm(obj, *options) # Print methods
methods = obj.methods - (options.include?(:more) ? [] : Object.methods)
filter = options.select {|opt| opt.kind_of? Regexp}.first
methods = methods.select {|name| name =~ filter} if filter
data = methods.sort.collect do |name|
method = obj.method(name)
args = "(" + case method.arity <=> 0
when 1
(”a”..(?a + method.arity - 1).chr).to_a.join(”, “)
when -1
(”a”..(?a - method.arity - 1).chr).to_a.join(”, “)
else
“”
end + “)”
klass = $1 if method.inspect =~ /Method: (.*?)#/
klass = $1 if klass =~ /((.*?))/
[name, args, klass]
end
max_name_length = data.collect {|item| item[0].size}.max
max_args_length = data.collect {|item| item[1].size}.max
data.each do |item|
print ” #{ANSI_BOLD}#{item[0].rjust(max_name_length)}#{ANSI_RESET}”
print “#{ANSI_GRAY}#{item[1].ljust(max_args_length)}#{ANSI_RESET}”
print ” #{ANSI_LGRAY}#{item[2]}#{ANSI_RESET} n”
end
data.size
end
Don’t try to understand it unless you can understand it :-)… just copy it to your .irbrc (you do have an irbrc file, don’t you?). And use it like this:



