Created
November 6, 2011 12:25
-
-
Save macosgrove/1342808 to your computer and use it in GitHub Desktop.
7L7W Ruby Day 2
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 | |
# @param hsh [Hash] | |
def initialize(hsh) | |
unless hsh.empty? | |
@children=[] | |
@node_name = hsh.keys.first | |
hsh[@node_name].each_pair { |k,v| @children.push(Tree.new(k=>v)) } | |
end | |
end | |
def visit_all(&block) | |
visit &block | |
children.each {|c| c.visit_all &block} | |
end | |
def visit(&block) | |
block.call self | |
end | |
end | |
family = {'grandpa'=>{'dad'=> {'child 1'=>{}, 'child 2'=>{}},'uncle'=>{'child 3'=>{}, 'child 4' =>{}}}} | |
ruby_tree = Tree.new(family) | |
puts "Visiting a node" | |
ruby_tree.visit {|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