Mike Kelly’s blog

What I think about…

Build a list of all files in a directory structure in Ruby

January 25th, 2008 in I'm A Scripter, Ruby

When testing web services it’s often nice to be able to process a set of XML files. In other automation it can be nice to process batches of files as well. For some reason I can never find the following code when I need it and I always have to re-code it from scratch. That’s always good practice, but it’s annoying when I need it quickly.

def getFiles(directory)
returnFiles = []
Dir.glob(directory + ‘/*’).each do | file |
if File.file?(file) then
returnFiles.push(file)
else
returnFiles.push(getFiles(file))
end
end
return returnFiles
end

So there it is. Google can now help me find my code whenever I need to build a list of all files in a directory structure.

Here is an example of how I might use that:

getFiles(”C:/Regression Files”).each do | testCaseFile |
resultsFile.puts(testCaseFile.to_s.split(’/')[-1].chomp +
‘, methodName, ‘ + object.methodName(testCaseFile))
end

2 Responses to “Build a list of all files in a directory structure in Ruby”

  • selie
    September 29th, 2008 at 1:13 pm

    FYI, this can be a one-liner if you’re looking for a specific file extension. The magic is in the ‘**’.

    def getFiles(directory)
    return Dir[directory + '/**/*.java']
    end

  • Mike Kelly
    September 29th, 2008 at 3:28 pm

    Cool. Thanks for the simplified version! Often I am…

Leave a Reply