Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
file
delete
communitycreator

What is File.delete() in Ruby?

okwudili onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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
Delete files in Ruby

Explanation

  • 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:

main.rb
test.txt
# Get file names
fn1 = "main.rb"
fn2 = "test.txt"
# Delete files
puts File.delete("test.txt")
puts File.delete("main.rb")
# Deleting the same file throws an error
puts File.delete("test.txt")
Deleting an already deleted file throws an error

RELATED TAGS

ruby
file
delete
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring