0
0
RubyHow-ToBeginner · 3 min read

How to Delete a File in Ruby: Simple Guide

In Ruby, you can delete a file using the File.delete method by passing the file path as an argument. This method removes the specified file from the filesystem immediately.
📐

Syntax

The basic syntax to delete a file in Ruby is:

  • File.delete(path): Deletes the file at the given path.

Here, path is a string representing the file's location.

ruby
File.delete('filename.txt')
💻

Example

This example creates a file, writes some text, deletes it, and then checks if the file still exists.

ruby
filename = 'example.txt'

# Create and write to the file
File.open(filename, 'w') do |file|
  file.puts 'Hello, Ruby!'
end

puts "File exists before deletion? #{File.exist?(filename)}"

# Delete the file
File.delete(filename)

puts "File exists after deletion? #{File.exist?(filename)}"
Output
File exists before deletion? true File exists after deletion? false
⚠️

Common Pitfalls

Common mistakes when deleting files in Ruby include:

  • Trying to delete a file that does not exist, which raises an Errno::ENOENT error.
  • Not having the right permissions to delete the file, causing a permission error.
  • Passing a directory path instead of a file path, which will raise an error.

To avoid errors, check if the file exists before deleting it.

ruby
filename = 'missing.txt'

# Wrong way: This will raise an error if file doesn't exist
# File.delete(filename)

# Right way: Check existence first
if File.exist?(filename)
  File.delete(filename)
  puts 'File deleted.'
else
  puts 'File does not exist.'
end
Output
File does not exist.
📊

Quick Reference

MethodDescription
File.delete(path)Deletes the file at the given path.
File.exist?(path)Returns true if the file exists, false otherwise.
File.unlink(path)Alias for File.delete, deletes the file.

Key Takeaways

Use File.delete('filename') to remove a file in Ruby.
Always check if the file exists with File.exist? before deleting to avoid errors.
File.delete immediately removes the file from the filesystem.
Deleting a non-existent file raises an error unless checked.
File.unlink is an alias for File.delete and works the same way.