Share This Article
If you want to delete a file in Ruby, you can use the File#delete
method.
File.delete("test.txt")
You can also delete a file using the FileUtils#rm
method from the FileUtils
module.
require "fileutils"
FileUtils.rm("test.txt")
Deleting Multiple Files
If you want to delete multiple files at once, you can use the FileUtils#rm_rf
method, which is also part of the FileUtils
module.
require "fileutils"
FileUtils.rm_rf(["test1.txt", "test2.txt"])
Both of these methods will delete the file permanently & there’s no way to undo it, so be careful.
Deleting Directories
Deleting directories is a bit different; you can’t use the File#delete
method for that.
Instead, you need to use the Dir#rmdir
method.
Dir.rmdir("some_directory")
The Dir#rmdir
method will only delete empty directories.
If you want to delete a non-empty directory, you can use the FileUtils#rm_rf
method.
Deleting Symbolic Links (Symlink)
You need to use the File#unlink
method when deleting symbolic links.
File.unlink("some_symlink")
Summary
In this article, you’ve learned how to delete a file, directory, or symlink using the File#delete
, FileUtils#rm
, FileUtils#rm_rf
, Dir#rmdir
and File#unlink
methods. You can check the official documentation here.