Created
May 9, 2011 12:55
-
-
Save mrc/962465 to your computer and use it in GitHub Desktop.
ruby tree ("seven languages")
This file contains 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
class Tree | |
attr_accessor :children, :name | |
def initialize(tree, name='root') | |
@name = name | |
@children = tree.map do |k,v| | |
Tree.new(v, k) | |
end | |
end | |
def visit_all(depth=0, &block) | |
visit(depth, &block) | |
children.each {|c| c.visit_all(depth+1, &block)} | |
end | |
def visit(depth=0, &block) | |
block.call(self, depth) | |
end | |
end | |
t = Tree.new({ | |
"Honor" => { | |
"America" => { | |
"Weapons" => {}, | |
"Wood working" => { | |
"Haircuts" => {}, | |
"Greatness Itself" => {}}}, | |
"Buffets" => { | |
"Teamwork" => {}, | |
"Selfishness" => {}}}}) | |
t.visit_all do |node, depth| | |
indent = ' ' * depth | |
puts indent + node.name | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The exercise was to extend the Tree class so you could pass a hash to the initialiser.