The file?()
method in Ruby is used to check whether a file exists and if is it a regular file. If this condition is met, it returns true
. Otherwise, it returns false
.
File.file?(file)
file
: This is the file we want to see if it exists and if it is a regular file.
This method returns a Boolean value. It returns true
if the condition is met, else false
.
# create file namesfn1 = "main.rb"fn2 = "test.txt"fn3 = "nothing"fn4 = "fake.txt"fn5 = "empty.txt"# check if files existsputs File.exists?(fn1)puts File.exists?(fn2)puts File.exists?(fn3)puts File.exists?(fn4)
text.txt
along with our source code file main.rb
.file?()
method to check if the names of the files exist. Next, we print the results to the console.