1

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?

JohnDoe
  • 825
  • 1
  • 13
  • 31

2 Answers2

2

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.

Jordan Running
  • 102,619
  • 17
  • 182
  • 182
  • Thx, but is this really an alternative to Dir.chdir? My idea is to go to directory where "myfile,txt" exist and to execute my script from there. I have relative paths within "myfile.txt" which are than not correctly interpreted. – JohnDoe Dec 08 '15 at 13:51
  • You can use `Dir.glob` in conjunction with `Dir.chdir` (or any other method that receives a path). I've edited my answer to include an example. – Jordan Running Dec 08 '15 at 15:00
0

you can use Pathname class to traverse through the directory structure

a = Pathname.new('/sourcecode')
a.children.each do |child1|
  child1.children.do |child2|
    if child2.file
       File.open(child2) do |f|
         f.each_line do |line|
         ...
    end 
  end 
end 
Asad Ali
  • 640
  • 6
  • 18