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"]
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With