Skip to content

Instantly share code, notes, and snippets.

@avihut
Created April 21, 2013 19:52

Revisions

  1. avihut created this gist Apr 21, 2013.
    41 changes: 41 additions & 0 deletions hashtree.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    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}