# How do I build a tree of directories?

**URL:** <https://www.ruby-forum.com/t/how-do-i-build-a-tree-of-directories/110293>\
**Category:** Ruby\
**Created:** [July 25, 2007, 12:06am UTC](https://www.ruby-forum.com/t/how-do-i-build-a-tree-of-directories/110293 "2007-07-25T00:06:23Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![thabenksta](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/97f17d/32.png) [@thabenksta](https://www.ruby-forum.com/u/thabenksta)\
**Post date:** [July 25, 2007, 12:06am UTC](https://www.ruby-forum.com/t/how-do-i-build-a-tree-of-directories/110293/1 "2007-07-25T00:06:23Z")

</div>

Hello. I need to send XML back to a client app listing all my  
directories and sub-directories on the server. The XML will look  
something like this:

 \<folder name="directory name" 

I’m doing this in Rails. I have a couple of questions:

1. In my controller, how do I use something like Find.find(path) to do  
this effectively? For example, do I need to make recursive calls to a  
method for each subdirectory encountered? Do I build an array of arrays  
for the sub-directories? A Hash?

2. Once my array of arrays or hash or whatever is built, what’s the best  
way to output this in my view?

Thanks in advance.

---

<div class="post-metadata">

**Author:** ![thabenksta](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/97f17d/32.png) [@thabenksta](https://www.ruby-forum.com/u/thabenksta)\
**Post date:** [July 26, 2007, 12:45am UTC](https://www.ruby-forum.com/t/how-do-i-build-a-tree-of-directories/110293/2 "2007-07-26T00:45:45Z")

</div>

On Jul 24, 3:06 pm, Ben K. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> ```
> </folder>
> 
> ```
> 
> I’m doing this in Rails. I have a couple of questions:

> 1. In my controller, how do I use something like Find.find(path) to do  
> this effectively? For example, do I need to make recursive calls to a  
> method for each subdirectory encountered?

You’d want to use one of the Dir methods; foreach(), glob()…

Entry = Struct.new(:dir,:children)

def recurse(path)

entry = Entry.new(path,[])

#no “.” or “…” dirs  
Dir[“#{path}/\*”].each do |e|  
if File.directory?(e)  
entry.children \<\< recurse(e)  
end  
end

entry

end

> Do I build an array of arrays for the sub-directories? A Hash?

Depends. If you just need the directory name and its children, then an  
array of arrays will work. If you need additional information, then  
use a Hash. Maybe a Struct (for fun).

> 1. Once my array of arrays or hash or whatever is built, what’s the best  
> way to output this in my view?

XML Builder, left as an exercise.

If you do not have additional requirements for the directory data,  
i.e. you just want to output it as XML, then I’d say write the XML  
with XML Builder as you recurse. Especially if your directory  
structure is big.
