Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Removing empty directories (non-recursive) (See related posts)

// Simple class to remove empty directories.

require 'fileutils'

class ReorgBot

  attr_accessor :path
  attr_accessor :dir

  def initialize(path)
    raise ArgumentError, "path '#{path}' does not exist!" unless File.exist?(path)
    raise ArgumentError, "path '#{path} is not a directory you dolt!" unless File.directory?(path)
    @path = path
    @dir = Dir.new(path)
  end

  def dirs
    @dir.select { |f| File.directory?(File.join(@path, f)) }
  end

  def empty_dirs
    dirs.select { |d| Dir[File.join(@path, d, '*')].empty? }
  end

  def non_empty_dirs
    dirs - empty_dirs
  end

  def remove_empty_dirs
    empty_dirs.each do |d|
      FileUtils.rm_rf(File.join(@path, d))
    end
  end
end

bot = ReorgBot.new('/tmp/reorg_test')
bot.remove_empty_dirs

Comments on this post

VidulPetrov posts on Sep 23, 2007 at 09:42
You already have this method:

require 'fileutils'

FileUtils.rmdir 'dirname' # Errno::ENOTEMPTY: Directory not empty

You need to create an account or log in to post comments to this site.


Click here to browse all 4861 code snippets

Related Posts