Insights on Ruby, Git, jQuery, Cappuccino, WordPress, Debian and OS X. Please subscribe if you find something useful!

Traversing Directories with Ruby

Posted: July 15th, 2008 | Author: Jerod | Filed under: Ruby | Comments Off

If you want to shove filenames of all files in a directory into an array, do:

# (absolute path)
files = Dir["/Users/jerod/src/**"]
# (relative path)
files = Dir[File.expand_path("~/src") + "/**"]
# (in ENV["PWD"], aka current directory)
files = Dir["**"]

If you want to shove filenames of all files in a directory recursively into an array, do:

# (absolute path)
files = Dir["/Users/jerod/src/**/**"]
# (relative path)
files = Dir[File.expand_path("~/src") + "/**/**"]
# (in ENV["PWD"], aka current directory)
files = Dir["**/**"]

It can’t get much easier than that.


Comments are closed.