changeset 22:e020410896ca

Add rewritten tree that takes a nested hash
author IBBoard <dev@ibboard.co.uk>
date Sat, 07 Jan 2017 21:04:20 +0000
parents 7e212cc7ec24
children 720e9201dd98
files 1-Ruby/tree.rb
diffstat 1 files changed, 15 insertions(+), 14 deletions(-) [+]
line wrap: on
line diff
--- a/1-Ruby/tree.rb	Sat Jan 07 20:36:33 2017 +0000
+++ b/1-Ruby/tree.rb	Sat Jan 07 21:04:20 2017 +0000
@@ -9,11 +9,16 @@
 class Tree
   attr_accessor :children, :node_name
   
-  def initialize(name, children=[])
-    @children = children
-    @node_name = name
+  def initialize(hash)
+    if hash.size == 1
+      @node_name = hash.keys[0]
+      @children = hash[@node_name].collect { |key,value| Tree.new({ key => value }) }
+    else
+      @node_name = 'Root'
+      @children = hash.collect { |key,value| Tree.new({ key => value }) }
+    end
   end
-  
+
   def visit_all(&block)
     visit &block
     children.each {|c| c.visit_all &block}
@@ -24,13 +29,9 @@
   end
 end
 
-ruby_tree = Tree.new( "Ruby", 
-  [Tree.new("Reia"), 
-   Tree.new("MacRuby")] )
-
-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}
+puts "Creating tree from hashes"
+hash_tree = Tree.new({'grandpa' => {'dad' => {'child1' => {}, 'child2' => {} }, 'uncle' => { 'child3' => {}, 'child4' => {} } } })
+hash_tree.visit_all {|node| puts node.node_name}
+puts "Testing non-tree hashes"
+hash_tree = Tree.new({'grandpa' => {'dad' => {'child1' => {}, 'child2' => {} }, 'uncle' => { 'child3' => {}, 'child4' => {} } }, 'other-person' => {'other-child' => {} } })
+hash_tree.visit_all {|node| puts node.node_name}