ruby list of files in directory include subfolders
To list all the files in a directory, including subfolders, in Ruby, you can use the following code:
def list_files(directory)
Dir.glob("#{directory}//*").select { |file| File.file?(file) }
end
Here's an explanation of each step:
The
Dir.glob
method is used to match file path patterns. In this case, we are using the pattern"#{directory}//"
, wheredirectory
is the input directory passed to the method. The"/"
pattern matches all files and directories recursively from the specified directory.The
Dir.glob
method returns an array of file paths that match the pattern.We then use the
select
method to filter the array of file paths. We only want to include files and exclude directories, so we use theFile.file?
method to check if each path corresponds to a file.The
select
method returns a new array containing only the file paths that pass the filter.Finally, the
list_files
method returns the array of file paths.
You can call the list_files
method with the desired directory as an argument to get a list of all the files in that directory and its subfolders.