Ruby deleting directories

I'm trying to delete a non-empty directory in Ruby and no matter which way I go about it it refuses to work. I have tried using FileUtils, system calls, recursively going into the given directory and deleting everything, but always seem to end up with (temporary?) files such as

.__afsECFC
.__afs73B9

Anyone know why this is happening and how I can go around it?


require 'fileutils'

FileUtils.rm_rf('directorypath/name')

Doesn't this work?


Safe method: FileUtils.remove_dir(somedir)


Realised my error, some of the files hadn't been closed. I earlier in my program I was using

File.open(filename).read

which I swapped for a

f = File.open(filename, "r")
while line = f.gets
    puts line
end
f.close

And now

FileUtils.rm_rf(dirname)

works flawlessly


I guess the best way to remove a directory with all your content "without using an aditional lib" is using a simple recursive method:

def remove_dir(path)
  if File.directory?(path)
    Dir.foreach(path) do |file|
      if ((file.to_s != ".") and (file.to_s != ".."))
        remove_dir("#{path}/#{file}")
      end
    end
    Dir.delete(path)
  else
    File.delete(path)
  end
end
remove_dir(path)

The built-in pathname gem really improves the ergonomics of working with paths, and it has an #rmtree method that can achieve exactly this:

require "pathname"

path = Pathname.new("~/path/to/folder").expand_path
path.rmtree