Ruby 删除目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12335611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby deleting directories
提问by Ced
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
我正在尝试删除 Ruby 中的非空目录,无论我采用哪种方式,它都拒绝工作。我曾尝试使用 FileUtils、系统调用、递归进入给定目录并删除所有内容,但似乎总是以(临时?)文件结束,例如
.__afsECFC
.__afs73B9
.__afsECFC
.__afs73B9
Anyone know why this is happening and how I can go around it?
任何人都知道为什么会发生这种情况以及我如何解决它?
采纳答案by Ced
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
完美无缺
回答by Ismael Abreu
require 'fileutils'
FileUtils.rm_rf('directorypath/name')
Doesn't this work?
这不行吗?
回答by merqlove
Safe method: FileUtils.remove_dir(somedir)
回答by JonatasTeixeira
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)

