28

Is there any class in ruby for listing all the files in a directory and all the files in the subdirectory?

1 Answer 1

64

You might look at Dir.glob. You can pass it the **/* path which will give you everything in the folder and its subdirectories:

records = Dir.glob("path/to/your/root/directory/**/*")
# Will return everything - files and folders - from the root level of your root directory and all it's subfolders
# => ["file1.txt", "file2.txt", "dir1", "dir1/file1.txt", ...]

Since you probably want a list of files, excluding folders, you can use:

records = Dir.glob("path/to/your/root/directory/**/*").reject { |f| File.directory?(f) }
4
  • If I want list everything in special directory not current directory , what can I do ?
    – amir amir
    Aug 24, 2011 at 20:56
  • 4
    Dir.glob("/path/to/my/directory/**/*") Aug 24, 2011 at 20:59
  • 1
    is it returns file extension?
    – rony36
    Jun 12, 2013 at 13:29
  • 6
    For future googlers, to get only files: Dir.glob("*/").reject {|f| File.directory?(f)} Nov 21, 2018 at 20:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.