In my Rails app I am trying to collect the paths to all the files contained in two different directories using Dir.glob
.
The following code works but is not very concise. Isn't there a way two match two patterns at once with Dir.glob
?
common_file_paths = Dir.glob("app/assets/mystuff/*").reject do |path|
File.directory?(path)
end
more_file_paths = Dir.glob("app/assets/mystuff/more/*").reject do |path|
File.directory?(path)
end
file_paths = common_file_paths + more_file_paths
Dir.glob
also accepts an array of patterns.
Dir.glob(["app/assets/mystuff/*", "app/assets/mystuff/more/*"])
this should do it for you .. tested it in my local machine and it works as expected.
lets say , you have the following directory and subdirectory :
z$ find deletpractic/
deletpractic/
deletpractic/sub_dir
deletpractic/sub_dir/file1_in_subdir.txt
deletpractic/sub_dir/file2_in_subdir.txt
deletpractic/text1
deletpractic/text2
deletpractic/text3
deletpractic/text4
deletpractic/text5
deletpractic/text6
deletpractic/text7
it pretty much boils down to this Dir.glob("/mydir/**/*")
[za]$ /usr/bin/ruby -rpp -e 'common_file_paths = Dir.glob("/dev/deletpractic/**/*").reject do |path| File.directory?(path) end ; pp common_file_paths'
Output :
["/dev/deletpractic/sub_dir/file1_in_subdir.txt",
"/dev/deletpractic/sub_dir/file2_in_subdir.txt",
"/dev/deletpractic/text1",
"/dev/deletpractic/text2",
"/dev/deletpractic/text3",
"/dev/deletpractic/text4",
"/dev/deletpractic/text5",
"/dev/deletpractic/text6",
"/dev/deletpractic/text7"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With