How to check if a file exists in Ruby
Overview
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.
Syntax
File.exists?(file_name)
Parameters
file_name: This is the name of the file whose existence we want to check.
Return value
This method returns a Boolean value. It returns true if the file exists, and false if it doesn’t.
Code example
main.rb
test.txt
# Create file namesfn1 = "main.rb"fn2 = "test.txt"fn3 = "fake.txt"fn4 = "empty.txt"# Check if the files existputs File.exists?(fn1)puts File.exists?(fn2)puts File.exists?(fn3)puts File.exists?(fn4)
Explanation
- Lines 2 to 5: We create some file names, of both files that exist and those that do not.
- Lines 8 to 11: We check if the files exist. Then, we print the results to the console.