Skip to content
Browse files

working implementation of construction of Tree with Hash literal, fin…

…ished with help from the reading group
  • Loading branch information...
1 parent c3fa405 commit 78f0a2af6b78a10065fbc99d41ef1ba2f1b9aecc @MikeChristianson committed Aug 2, 2012
Showing with 43 additions and 0 deletions.
  1. +43 −0 Ruby/Day-2/tree4.rb
View
43 Ruby/Day-2/tree4.rb
@@ -0,0 +1,43 @@
+#---
+# Excerpted from "Seven Languages in Seven Weeks",
+# published by The Pragmatic Bookshelf.
+# Copyrights apply to this code. It may not be used to create training material,
+# courses, books, articles, and the like. Contact us if you are in doubt.
+# We make no guarantees that this code is fit for any purpose.
+# Visit http://www.pragmaticprogrammer.com/titles/btlang for more book information.
+#---
+class Tree
+ attr_accessor :children, :node_name
+
+ def initialize(family)
+ family.keys.each do |key|
+ @node_name = key
+ @children = []
+ unless node_name.nil?
+ child_hash = family.fetch node_name
+ child_hash.each do |k,v|
+ children.push Tree.new({k => v})
+ end
+ end
+ 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_tree = {'grandpa' => { 'dad' => {'child 1' => {}, 'child 2' => {} }, 'uncle' => {'child 3' => {}, 'child 4' => {} } } }
+ruby_tree = Tree.new(family_tree)
+
+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}

0 comments on commit 78f0a2a

Please sign in to comment.
Something went wrong with that request. Please try again.