简体   繁体   中英

How to match multiple patterns with Dir.glob?

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也接受一系列模式。

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"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM