i need a recursive function to list files in a folder:
def procdir(dirname)
data = ''
Dir.foreach(dirname) do |dir|
dirpath = dirname + '/' + dir
if File.directory?(dirpath) then
if dir != '.' && dir != '..' then
#puts "DIRECTORY: #{dirpath}" ;
procdir(dirpath)
end
else
data += dirpath
end
end
return data
end
but the result: is null
Stdlib Dir#glob
recurses when you give it the **
glob.
def procdir(dir)
Dir[ File.join(dir, '**', '*') ].reject { |p| File.directory? p }
end
Use the find
module:
require 'find'
pathes = []
Find.find('.') do |path|
pathes << path unless FileTest.directory?(path)
end
puts pathes.inspect
Old thread but perhaps someone might find it useful:
array_of_all_files = Dir
.glob("**/*")
.reject { |file_path| File.directory? file_path }
It looks like there are a couple of problems with the recursion:
- The
else
clause appears to associated with the wrong if
. It needs to be associated with the first if
.
- The result of the recursive
procdir
call should be added to data
.
If you indent the code a little more cleanly, it would probably be easier to spot problems like that. The following contains the two fixes:
def procdir(dirname)
data = ''
Dir.foreach(dirname) do |dir|
dirpath = dirname + '/' + dir
if File.directory?(dirpath) then
if dir != '.' && dir != '..' then
#puts "DIRECTORY: #{dirpath}" ;
data += procdir(dirpath)
end
else
data += dirpath
end
end
return data
end
If you know the file extensions you will have just use this:
Dir[Rails.root.join('config/locales/**/*.{rb,yml}')]