How to Delete a File in Ruby?

here I learn to simple ruby file delete or truncate if exists without failing on error.

Delete a File in Ruby

The following articles learn how to delete files and folders and files that you no longer required in your Ruby application. Deleting or Removing single file in Rubys is easy and straightforward, with File.delete. This way to Deletes the named files, returning the number of names passed as arguments. Raises an exception on any error.

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

Removing a folder tree is also straightforward and easy with FileUtils.remove_dir, which delete directory recursively remove/deletes the data contents of a folder. This ways ignores all the StandardError if force fully (second parameter) is the boolean value like as a true.

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

Also Read : All coins and Cryptocurrency Data API PHP, Ruby, Python

Ruby provides different ways for removing folders and files, but mostly i use remove_dir. Dir.delete as well as FileUtils.rmdir will only work if the folder is already null or empty. The rm_r as well as rm_rf defined in FileUtils are same to same to remove_dir.

Handling the Errno::ENOENT Exception

here first of all file.open ruby and then display file delete exception.

begin
  File.open('pakainfo.txt', 'r') do |f|
    # do something with file
    File.delete(f)
  end
rescue Errno::ENOENT
end

Leave a Comment