Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 298
Tintin81 Avatar asked Aug 03 '16 13:08

Tintin81


2 Answers

Dir.glob also accepts an array of patterns.

Dir.glob(["app/assets/mystuff/*", "app/assets/mystuff/more/*"])
like image 180
koffeinfrei Avatar answered Nov 18 '22 02:11

koffeinfrei


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"]
like image 1
z atef Avatar answered Nov 18 '22 04:11

z atef