I have a directory structure, for example like this:
+SOURCE_CODE
+ MODULE_A
-myfile.txt
+ MODULE_B
-myfile.txt
+ MODULE_C
-myfile.txt
Now I would like to do "Dir.chdir" into each of these directories (MODULE_A, MODULE_B) and than open the "myfile.txt" where I than operate with the strings within these files. It should be something like this:
Dir.chdir "../SOURCE_CODE/MODULE_*/"
File.open("myfile.txt") do |f|
f.each_line do |line|
......
I know, it is not possible to use wildcards with "Dir.chdir". But is there an alternative way?
You can use wildcards with Dir.glob
:
Dir.glob("../SOURCE_CODE/MODULE_*/myfile.txt") do |filename|
File.open(filename) do |f|
f.each_line do |line|
# ...
end
end
end
You can do anything you want inside the block:
Dir.glob("../SOURCE_CODE/MODULE_*/") do |dirname|
Dir.chdir(dirname)
File.open("myfile.txt") do |f|
f.each_line do |line|
# ...
end
end
end
You may need to supply an absolute path to Dir.glob
for Dir.chdir
to work as expected; I'm not sure. File.expand_path
is handy for this.