Ruby - Delete a File

1. Introduction

Sometimes, when working with file operations, it's necessary to delete a file from the system. Ruby offers a simple and straightforward way to handle file deletions using its built-in File class.

Deleting a file means removing it permanently from the storage system. This operation is irreversible, and once executed, the file cannot be recovered unless there's a backup or some recovery mechanism in place.

2. Program Steps

1. Ensure the file you want to delete exists.

2. Use the File class's delete method to remove the file.

3. Confirm the deletion.

3. Code Program

# Check if the file exists before attempting to delete
if File.exist?('sample.txt')
  # Delete the file using the File class's delete method
  File.delete('sample.txt')
  puts "sample.txt has been deleted."
else
  puts "File not found."
end

Output:

sample.txt has been deleted.

Explanation:

1. Before attempting to delete a file, it's a good practice to check if it exists to avoid possible errors. This is done using the File.exist? method, which returns true if the file exists and false otherwise.

2. If the file is found, the File.delete method is used to delete it. This method takes the filename as an argument.

3. After deletion, a confirmation message "sample.txt has been deleted." is displayed.

4. If the file is not found, a message "File not found." is displayed.

It's important to be cautious when deleting files, as this operation is permanent and the deleted file cannot be recovered through this program.


Comments