view 1-Ruby/tree.rb @ 78:75dbcd30dee5

Add final exercise code from Erlang It works, but it never made much sense because there was too much magic
author IBBoard <dev@ibboard.co.uk>
date Sat, 01 Jun 2019 20:10:37 +0100
parents e020410896ca
children
line wrap: on
line source

#---
# 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(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}
  end
  
  def visit(&block)
    block.call self
  end
end

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}