Aditya Bhat
Aditya Bhat

Reputation: 97

get relative paths to files in ruby

I have a folder structure as follows:

.
└── FolderA
    ├── a.cpp
    ├── b.cpp
    ├── c.cpp
    ├── FolderB
    │   ├── trial.cpp
    │   └── trial1.cpp
    └── FolderC
        └── srcFolder
            └── anothercppfile.cpp

I wanted to store the names of all .cpp files which are present in FolderA in an array. I have to ensure that I preserve the relative paths of the files which are present in folders inside FolderA.

I can use:

require 'find'
cpp_file_paths = []
Find.find('path/to/search') do |path|
  cpp_file_paths << path if path =~ /.*\.cpp$/
end 

But I do not get the relative paths. I am unsure on how to proceed. The final array must be:

["a.cpp",
 "b.cpp",
 "c.cpp",
 "/FolderB/trial.cpp",
 "/FolderB/trial1.cpp",
 "/FolderC/srcFolder/anothercppfile.cpp"]

Upvotes: 2

Views: 1411

Answers (1)

Stefan
Stefan

Reputation: 114158

You can use Dir.glob:

Starting with Ruby 2.5 there's a base argument:

cpp_file_paths = Dir.glob('**/*.cpp', base: 'FolderA')
#=> ["a.cpp", "b.cpp", "c.cpp", "FolderB/trial.cpp", "FolderB/trial1.cpp", "FolderC/srcFolder/anothercppfile.cpp"]

For older Rubies, you can chdir into the base directory:

Dir.chdir('FolderA') do
  cpp_file_paths = Dir.glob('**/*.cpp') #=> ["a.cpp", "b.cpp", "c.cpp", "FolderB/trial.cpp", "FolderB/trial1.cpp", "FolderC/srcFolder/anothercppfile.cpp"]
end

Note that the paths are relative, i.e. they don't start with a /. Passing a block to chdir ensures that the current directory is restored afterwards (thanks Arup Rakshit).

Upvotes: 12

Related Questions