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
Use the
find
module:It looks like there are a couple of problems with the recursion:
else
clause appears to associated with the wrongif
. It needs to be associated with the firstif
.procdir
call should be added todata
.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:
Old thread but perhaps someone might find it useful:
array_of_all_files = Dir .glob("**/*") .reject { |file_path| File.directory? file_path }
Stdlib
Dir#glob
recurses when you give it the**
glob.If you know the file extensions you will have just use this:
Dir[Rails.root.join('config/locales/**/*.{rb,yml}')]