What is File.file?() method in Ruby?
Overview
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.
Syntax
File.file?(file)
Parameter
file: This is the file we want to see if it exists and if it is a regular file.
Return value
This method returns a Boolean value. It returns true if the condition is met, else false.
Code example
main.rb
test.txt
# 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)
Explanation
- Lines 1–2: We create a file called
text.txtalong with our source code filemain.rb. - Lines 2–6: We initialize the names of the files.
- Lines 9–12: We use the
file?()method to check if the names of the files exist. Next, we print the results to the console.