Directory Trees

Tuesday, March 06, 2007 by Nate Murray.

Below is a code snippet for putting directory tree into a data structure. Basically what I wanted was for each folder to be a hash with the key being the folder name and the value was an array of the files and folders it contains. For example: The folders:

       content/policy
       content/policy/privacy_policy.txt
       content/policy/about_us.txt
       content/policy/mean_policy
       content/policy/mean_policy/nice_people.txt
       content/policy/mean_policy/mean_people.txt
       content/index.txt
       content/content
       content/content/misc
Creates the structure:
      {"content"=>
         [{"content"=>[{"misc"=>[]}]},
           "index.txt",
          {"policy"=>
            ["about_us.txt",
            {"mean_policy"=>["mean_people.txt", "nice_people.txt"]},
             "privacy_policy.txt"]}]}
The recursive code snippet is posted below:
    def content_files_in_dir(dir, results = {}, opts = {})
      return nil unless File.exist?(dir)
      entries = Dir.entries(dir).delete_if { |f| f =~ /^\./ }

      key = File.basename(dir)
      values = []

      entries.each do |entry|
        full_entry = File.join(dir, entry)
        values << ( File.directory?(full_entry) ?
          content_files_in_dir(full_entry, results, opts) :
          entry )
      end
      { key => values }
    end

Labels: , ,

Who we are:
The Pasadena Ruby Brigade is a group of programmers who are interested in Ruby. We enjoy sharing our ideas and code with anyone who is interested in this wonderful programming language.

Who can join:
Anyone! Just head over to our mailing list and drop us an email.

What we do:
We recently started a project over at RubyForge. This project is a group of programs written and maintained by our members that we thought could be beneficial to the whole community.

Projects

Downloads

Recent Posts

Archives