Created
April 21, 2013 19:52
-
-
Save avihut/5430842 to your computer and use it in GitHub Desktop.
Tree from Hash
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
class Tree | |
attr_accessor :children, :node_name | |
def initialize(name, children=[]) | |
@node_name = name | |
@children = children | |
end | |
def visit_all(&block) | |
visit &block | |
visit_children &block | |
end | |
def visit_children(&block) | |
children.each {|c| c.visit_all &block} | |
end | |
def visit(&block) | |
block.call self | |
end | |
end | |
def tree_from_hash(h) | |
tree_from_hash = [] | |
for name in h.keys do | |
tree_from_hash.push(Tree.new(name, tree_from_hash(h[name]))) | |
end | |
end | |
ruby_tree = tree_from_hash({'grandpa'=>{'dad'=>{'child 1'=>{}}}})[0] | |
puts "Visiting a node" | |
ruby_tree.visit {|node| puts node.node_name} | |
puts | |
puts "Visiting only children" | |
ruby_tree.visit_children {|node| puts node.node_name} | |
puts | |
puts "Visiting entire tree" | |
ruby_tree.visit_all {|node| puts node.node_name} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment