Check if a File Exists in Ruby

  1. Create a Sample Folder
  2. Use File.file? to Check if a File Exists in Ruby
  3. 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
Write for us
DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Ruby File

  • Ruby List File in Folder
  • Read Lines of a Files in Ruby
  • Write to a File in Ruby