Ruby function list file recursively

2020-07-14 05:14发布

问题:

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

回答1:

Stdlib Dir#glob recurses when you give it the ** glob.

def procdir(dir)
  Dir[ File.join(dir, '**', '*') ].reject { |p| File.directory? p }
end


回答2:

Use the find module:

require 'find'

pathes = []
Find.find('.') do |path|
  pathes << path unless FileTest.directory?(path)
end

puts pathes.inspect


回答3:

Old thread but perhaps someone might find it useful:

array_of_all_files = Dir .glob("**/*") .reject { |file_path| File.directory? file_path }



回答4:

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


回答5:

If you know the file extensions you will have just use this:

Dir[Rails.root.join('config/locales/**/*.{rb,yml}')]