The File.delete()
method in Ruby deletes the named files specified to it. It returns the number of names passed as arguments. If we try to delete an already deleted file, the method throws an error.
File.delete(file_name)
The number of parameters passed to the delete()
method is returned.
We create the file test.txt
along with main.rb
, and main.rb
contains our application code.
Lines 2 to 3: We obtain the names of our files.
Lines 6 to 7: We delete the files using the delete()
method.
Note: Deleting an already deleted file results in an error. See the example below:
# Get file namesfn1 = "main.rb"fn2 = "test.txt"# Delete filesputs File.delete("test.txt")puts File.delete("main.rb")# Deleting the same file throws an errorputs File.delete("test.txt")