Reputation: 5705
I have a lot of directories that are empty, save for other empty directories inside them. They are also mixed with other directories that do have files in them, so I want to only delete the empty directories and their (now empty) parents.
I’ve come up with this:
empty_dirs = -> { Dir.glob("#{dir}/**/*").select { |d| File.directory?(d) && Dir.empty?(d) } }
empty_dirs.call.each { |d| Dir.rmdir(d) } until empty_dirs.call.empty?
This works fine, but I was wondering if there’s a standard way — like FileUtils.rmdir_r(dir)
— instead of having to write a loop.
Upvotes: 0
Views: 459
Reputation: 121000
Dir.rmdir
is a wrapper for shell’s rmdir
which fails when the directory is not empty (ruby version raises an exception)
Errno::ENOTEMPTY: Directory not empty @ dir_s_rmdir
One might take advantage of this
Dir.glob("#{dir}/**/*").
select(&File.method(:directory?)).
sort_by(&:length). # to start as deep as possible
reverse. # longest first
each do |directory|
Dir.rmdir(directory) rescue :skipped
end
Upvotes: 3