'ruby - delete all the files in the directory

I've create a csv file in directory and now in some other action in my controller I'm reading that file and code it, then close the file and finally delete that file in directory. while deleting I'm Getting the error "Permission denied @ apply2files"

dir_path = "path_to_dir/"
file = "myfile.csv"

csv_file = File.open("#{dir_path}/#{file}", "r")

# Code...

csv_file.close
Delete the file in directory

I've used many method but all of them giving me same error

# First Method
Dir.glob("#{dir_path}").each do |file|
    File.delete(file)
end

# Second Method
Pathname.new(dir_path).children.each { |p| p.rmtree }

# Third Method
Dir.foreach(dir_path) {|f| File.delete("#{dir_path}/#{f}") if f != '.' && f != '..'}

#  Fourth Method
if File.directory?(dir_path)
    Dir.foreach(dir_path) do |file|
        if ((file.to_s != ".") and (file.to_s != ".."))
            self.deleteFilesInDirectory("#{dir_path}/#{file}")
        end
    end
    Dir.delete(dir_path)
else
    File.delete(dir_path)
end

All of them giving me same error

Can anyone help me to delete all files from a specific directory?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source