Skip to content

Instantly share code, notes, and snippets.

@ngm
Created November 27, 2011 12:42
Show Gist options
  • Save ngm/1397509 to your computer and use it in GitHub Desktop.
Save ngm/1397509 to your computer and use it in GitHub Desktop.
Seven Languages in Seven Weeks - Ruby - Day 2 - Tree
class Tree
attr_accessor :children, :node_name, :depth
def initialize(structure, depth)
@node_name = structure.keys.first
@depth = depth
@children = structure.values.first.map { |name,child| Tree.new({name,child}, depth+1) }
end
def visit_all(&block)
visit &block
children.each {|c| c.visit_all &block}
end
def visit(&block)
block.call self
end
end
treeHash =
{
'grandpa' =>
{
'dad' =>
{
'child1' => {},
'child2' => {}
},
'uncle' =>
{
'child3' => {},
'child4' => {}
}
}
}
tree = Tree.new(treeHash, 1)
puts "Visiting entire tree"
puts
tree.visit_all do |node|
(node.depth-1).times { print "--" }
puts node.node_name
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment