#!/usr/bin/env ruby class Tree attr_accessor :name, :children def initialize(hash = {}) pair = hash.first if pair @name = pair[0] @children = [] pair[1].each do |key, value| @children.push(Tree.new( {key => value} )) end else @name = nil @children = nil end end def visit_all(&block) visit(&block) children.each {|x| x.visit_all(&block) if x} end def visit(&block) block.call self end end ruby_tree = Tree.new({"Ruby" => {"Reia" => {"MacRuby" => {}}, "Waka" => {"Blr" => {}}}}) puts "Visiting a node" ruby_tree.visit {|node| puts node.name} puts puts "Visiting entire tree" ruby_tree.visit_all {|node| puts node.name}