Skip to content

Instantly share code, notes, and snippets.

@YenTheFirst
Created June 23, 2011 18:34
Show Gist options
  • Save YenTheFirst/1043215 to your computer and use it in GitHub Desktop.
Save YenTheFirst/1043215 to your computer and use it in GitHub Desktop.
Pretty Ruby Methods
#Pretty Methods
#you can call any_object.pretty_methods
#it will return a hash of classes from that objects ancestor chain, and all the method names (as symbols) of that object which are created by that ancestor.
#example: 5.pretty_methods: {Fixnum=>[:%, %+, :odd? ....], Integer=>[:ceil,:round,...],...Kernel=>[:is_a?, :taint, ...]
#you can pass the parameter 'false' to get back classes as strings, instead of Class objects
#add 'require <path>/pretty_methods.rb' to your .irbrc file, and have the fun by default!
class Object
def pretty_methods(raw_classes=true)
meth = methods.group_by {|m| method(m).owner}
parents = self.class.ancestors
sorted = meth.map {|k,v| [k,v.sort]}.sort_by {|(k,v)| parents.index(k)}
sorted.map! {|(k,v)| [k.to_s,v]} unless raw_classes
Hash[*sorted.flatten(1)]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment