i am quite new to ruby and I was wondering if there is a method in ruby
to get a list of folders and subfolders.
e.g.: I have a ‘root’ directory and some sub directories and finaly some
data files.
—root
|—sub1
| |----sub1A
| | |----data.txt
| |
| |----sub1B
| |----data.txt
|
|—sub2
| |----sub2A
| | |----data.txt
. .
. .
. .
and so on.
is there a way in ruby to get a list of all subdirectories, or maybe a
string to each data.txt (this name doesnot change)
The problem is, that i don’t know how many ‘data.txt’ there are , and so
i would need a method that searches in all subdirectories(starting at
‘root’) for this file and returns an array of strings with the path to
each file.
is there a way in ruby to get a list of all subdirectories, or maybe a
string to each data.txt (this name doesnot change)
The problem is, that i don’t know how many ‘data.txt’ there are , and so
i would need a method that searches in all subdirectories(starting at
‘root’) for this file and returns an array of strings with the path to
each file.
files = Dir[ ‘root/**/data.txt’ ]
Is there maybe another way to do this?
Yes, you can also use Find:
require ‘find’
Find.find( ‘root’ ) {|f| p f if File.basename(f) == “data.txt”}
def search( directory, pattern )
result = Array.new
Dir.glob("#{directory}/*") do |file|
next if file[0] == ?.
if File.directory? file
result.push(*search(file, pattern))
elsif file =~ pattern
result << file
end
end
result
end
puts search(“root”, /data.txt\Z/)
Hope that helps.
James Edward G. II
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.