Last active
December 17, 2015 12:19
-
-
Save rochefort/5608744 to your computer and use it in GitHub Desktop.
show ruby classes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
class TreeNodeData < Array | |
def <<(ary) | |
raise ArgumentError unless ary.size == 2 | |
super | |
end | |
def child_data | |
self[0] | |
end | |
def parent_data | |
self[1] | |
end | |
def root? | |
self.parent_data.nil? | |
end | |
end | |
class Tree | |
def initialize | |
@data = Array.new | |
end | |
def <<(ary) | |
@data << TreeNodeData.new(ary) | |
end | |
def to_s(indent=' ') | |
@indent = indent | |
root_nodes = @data.select(&:root?) | |
puts_hierarchy(root_nodes) | |
end | |
private | |
def puts_hierarchy(nodes, depth=0) | |
return nodes if nodes.size.zero? | |
nodes.sort_by{ |x| x.child_data.to_s }.each do |node| | |
puts "#{@indent*depth}#{node.child_data}" | |
children = @data.select { |elm| elm.parent_data == node.child_data } | |
puts_hierarchy(children, depth+1) | |
end | |
end | |
end | |
if __FILE__ == $0 | |
tree = Tree.new | |
Module.constants.each do |elm| | |
const = eval(elm.to_s) | |
tree << [const, const.superclass] if const.respond_to? :superclass | |
end | |
puts tree | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment