We can check if a file exists in Ruby by using the exists?()
method of the File class.
This method returns a Boolean value signifying if the file exists or not.
File.exists?(file_name)
file_name
: This is the name of the file whose existence we want to check.
This method returns a Boolean value. It returns true
if the file exists, and false
if it doesn’t.
# Create file names fn1 = "main.rb" fn2 = "test.txt" fn3 = "fake.txt" fn4 = "empty.txt" # Check if the files exist puts File.exists?(fn1) puts File.exists?(fn2) puts File.exists?(fn3) puts File.exists?(fn4)
RELATED TAGS
CONTRIBUTOR
View all Courses