How to Check if a File Exists in Ruby
Stewart Nguyen
Feb 02, 2024
- Create a Sample Folder
-
Use
File.file?
to Check if a File Exists in Ruby -
Use
File.exist?
to Check if a File Exists in Ruby
This article will instruct how to check if a file exists in Ruby.
Create a Sample Folder
Please execute these commands in the terminal at your current directory in advance.
mkdir sample_folder
touch sample_folder/my_file.txt
mkdir sample_folder/my_folder
Use File.file?
to Check if a File Exists in Ruby
Method File.file?
takes a file path as the argument. It returns true
when the file exists; otherwise, false
.
When the file exists,
File.file?('sample_folder/my_file.txt')
Output:
true
When the file does not exist,
File.file?('sample_folder/my_another_file.txt')
Output:
false
Use File.exist?
to Check if a File Exists in Ruby
Method File.exist?
takes a file path as the argument. It returns true
when the file exists; otherwise, false
.
When the file exists,
File.file?('sample_folder/my_file.txt')
Output:
true
When the file does not exist,
File.file?('sample_folder/my_another_file.txt')
Output:
false
File.exist?
is not only used to check for a file but also to check if a folder exists.
Example:
File.exist?('sample_folder/my_folder')
Output:
true