Ruby deleting directories

RubyDirectory

Ruby Problem Overview


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?

Ruby Solutions


Solution 1 - Ruby

require 'fileutils'

FileUtils.rm_rf('directorypath/name')

Doesn't this work?

Solution 2 - Ruby

Solution 3 - Ruby

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

Solution 4 - Ruby

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)

Solution 5 - Ruby

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCedView Question on Stackoverflow
Solution 1 - RubyIsmaelView Answer on Stackoverflow
Solution 2 - RubymerqloveView Answer on Stackoverflow
Solution 3 - RubyCedView Answer on Stackoverflow
Solution 4 - RubyJonatasTeixeiraView Answer on Stackoverflow
Solution 5 - RubyAlexanderView Answer on Stackoverflow