How to Delete File in Ruby
We will introduce how to delete files in Ruby.
Delete a File in Ruby
When we are working on an application that requires multiple files, there are sometimes a lot of files that take too much space and make our application slow. We may want to delete the files that are no longer useful.
There can be two situations: deleting a single file or multiple or all files from the folder. Ruby provides some easy methods that can be used for both situations, and we will discuss them in detail.
Delete a Single File in Ruby
For example, we have a file in a Directory E
with the following path E:\File Management\Files\ called "property1.pdf."
. Now we want to delete this file from our device. We can use the following delete
command to perform this task in the ruby programming language.
Command:
# ruby
File.delete('E:\\File Management\\Files\\property1.pdf')
When we run this command, it will delete the file. Using this method, we can easily delete files one by one.
For example, if a user deletes their file on our application, we want to delete it from our system too. We can use this command and provide the path to the file to will delete the file.
Delete a Folder in Ruby
Now, if there is a situation where our user wants to delete his account, and with his account, we want to delete all the files associated with his account as well.
Ruby has another method, fileutils
, that is used for the deleting of a folder. Let’s go through an example and try to delete the user husnain
folder.
# ruby
FileUtils.rm_rf('E:\\File Management\\User\\husnain\\')
This command will delete the entire folder and all the files inside it.