Skip to content

How to Delete a File in Ruby

Last updated on November 17, 2022

The following tutorial describes how to delete files and directories that you no longer need in your application. Removing a single file in Ruby is simple and straightforward, with File.delete. This method Deletes the named files, returning the number of names passed as arguments. Raises an exception on any error.

  File.delete(path_to_file) if File.exist?(path_to_file)

Removing a directory tree is also straightforward and simple with FileUtils.remove_dir, which recursively deletes the contents of a directory. This method ignores StandardError if force(second parameter) is true.

  FileUtils.remove_dir(path_to_directory) if File.directory?(path_to_directory)

Ruby provides several methods for removing directories, but mostly we use remove_dir. Dir.delete and FileUtils.rmdir will only work if the directory is already empty. The rm_r and rm_rf defined in FileUtils are similar to remove_dir.

0 0 votes
Article Rating
Subscribe
Notify of
guest

2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments