Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby function list file recursively

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

like image 813
indi Avatar asked Mar 19 '13 14:03

indi


2 Answers

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

def procdir(dir)
  Dir[ File.join(dir, '**', '*') ].reject { |p| File.directory? p }
end
like image 137
dbenhur Avatar answered Nov 15 '22 11:11

dbenhur


Use the find module:

require 'find'

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

puts pathes.inspect
like image 41
ckruse Avatar answered Nov 15 '22 10:11

ckruse