Created
November 27, 2011 12:42
-
-
Save ngm/1397509 to your computer and use it in GitHub Desktop.
Seven Languages in Seven Weeks - Ruby - Day 2 - Tree
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, :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