Ruby: Deleting Files

It is very easy to delete files using ruby. I will show you how to delete a single file and a directory full of files using ruby.

1. Deleting a single file

Let us say that I have a file at C:\Users\adhithya\desktop\ called "hello_world.txt" that I want to delete using ruby.

To delete a file you need to use #delete command of the File class.

File.delete("C:\\Users\\adhithya\\desktop\\hello_world.txt")

2. Deleting a Directory/Folder

You can use ruby's "fileutils" module to achieve deleting folders/directories.

Let us say that I have to delete a folder at C:\Users\adhithya\desktop\ called "demo" that needs to be deleted.

You can use the #rm_rf method of the fileutils module to achieve that

require 'fileutils'

FileUtils.rm_rf("C:\\Users\\adhithya\\desktop\\demo\")