I am attempting to delete files based on a pattern from all directories contained in a given path. I have the following but it acts like an infinite loop. When I cancel out of the loop, no files are deleted. Where am I going wrong?
def recursive_delete (dirPath, pattern)
if (defined? dirPath and defined? pattern && File.exists?(dirPath))
stack = [dirPath]
while !stack.empty?
current = stack.delete_at(0)
Dir.foreach(current) do |file|
if File.directory?(file)
stack << current+file
else
File.delete(dirPath + file) if (pattern).match(file)
end
end
end
end
end
# to call:
recursive_delete("c:\Test_Directory\", /^*.cs$/)
You don’t need to re-implement this wheel. Recursive file glob is already part of the core library.
Dir#glob lists files in a directory and can accept wildcards.
**is a super-wildcard that means “match anything, including entire trees of directories”, so it will match any level deep (including “no” levels deep:.csfiles inC:\Test_Directoryitself will also match using the pattern I supplied).@kkurian points out (in the comments) that
File#deletecan accept a list, so this could be simplified to: