What is File.delete() in Ruby?
Overview
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.
Syntax
File.delete(file_name)
Parameters
- file_name: This is the name of the file we want to delete.
Return value
The number of parameters passed to the delete() method is returned.
Example
main.rb
test.txt
Explanation
-
We create the file
test.txtalong withmain.rb, andmain.rbcontains 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:
main.rb
test.txt
# 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")