
In a recent application I am building I needed to pull file names and directory names from a local directory. I searched all over the net for this and found nothing. After reviewing a few of rails built in functions I came across Dir.glob(). If you feed this method a path to a directory it will then come back with an array of the names and directories listed.
So lets say I am going to tell Dir.glob to look in my “files” folder. The path I need to feed it is starting from the root of my app so the path would be “public/files/”.
1 | @files = Dir.glob("public/files/*") |
I added “*” so I can pull all files and dir’s back. If I just want to pull PDF’s back I can use this:
1 | @files = Dir.glob("public/files/*.pdf") |
That will show all PDF’s in that folder. You may also give it a file name and just pull one file out.
Anyway back to example one, I am looking for all files and all directories in the folder “files”. Below is the array I get back from @files.
1 2 3 4 5 6 7 8 9 10 11 | for file in @files puts file end #==== Output is: public/files/test1.gif public/files/test2.gif public/files/folder |
This is the best way I have found for pulling files from a directory and listing them in an array.
Need more help with rails? Here is a great book that i recommend for all new and old rails developers: Beginning Ruby: From Novice to Professional



Leave A Comment!