Ruby List File in Folder

  1. Create a Sample Folder
  2. Use Dir::[] to List All Files in a Folder
  3. Use Dir.glob to List All Files in a Folder

This article will introduce different ways to list all files in a particular folder in Ruby.

Create a Sample Folder

Please use these command lines to create a folder structure in your current directory.

mkdir parent_folder
touch parent_folder/music_1.txt
touch parent_folder/music_2.txt

mkdir parent_folder/child_folder
touch parent_folder/child_folder/doc_1.txt
touch parent_folder/child_folder/doc_2.txt

Use Dir::[] to List All Files in a Folder

Use Dir[<path_to_folder>/*], it returns an array containing all file names and folder names inside path_to_folder.

Afterward, we’ll use the File.file? method to select the file names from the result.

Example:

files = Dir['parent_folder/*'].select { |path| File.file?(path) }
puts files

Output:

parent_folder/music_1.txt
parent_folder/music_2.txt

To list files recursively inside subfolder, we can apply this pattern:

files = Dir['parent_folder/**/*'].select { |path| File.file?(path) }
puts files

Output:

parent_folder/music_1.txt
parent_folder/music_2.txt
parent_folder/child_folder/doc_2.txt
parent_folder/child_folder/doc_1.txt

Use Dir.glob to List All Files in a Folder

Calling Dir.glob is equivalent to calling Dir[<path_to_folder>].

Example:

files = Dir.glob('parent_folder/**/*').select { |path| File.file?(path) }
puts files

Output:

parent_folder/music_1.txt
parent_folder/music_2.txt
parent_folder/child_folder/doc_2.txt
parent_folder/child_folder/doc_1.txt
Write for us
DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Ruby File

  • Check if a File Exists in Ruby
  • Read Lines of a Files in Ruby
  • Write to a File in Ruby