Ruby - Check if a File Exists

1. Introduction

Working with files is a common task in programming, and there are occasions when you need to verify if a particular file exists in the file system. Ruby provides an intuitive way to accomplish this using the File class. This article will walk you through the process of checking if a file exists using Ruby.

Checking if a file exists means determining whether a file with the specified name or path is present in the filesystem. This is particularly useful when you want to avoid file-related errors in your programs.

2. Program Steps

1. Load the required library/module.

2. Specify the file name/path to be checked.

3. Use the exist? method from the File class to verify the file's existence.

4. Print the result based on the outcome of the check.

3. Code Program

# Specify the file name/path to be checked
file_name = "sample.txt"
# Check if the file exists
if File.exist?(file_name)
  puts "The file '#{file_name}' exists!"
else
  puts "The file '#{file_name}' does not exist!"
end

Output:

The file 'sample.txt' exists!
Or
The file 'sample.txt' does not exist!

Explanation:

1. file_name = "sample.txt": Here, we specify the name or path of the file we want to check.

2. File.exist?(file_name): The exist? method from the File class is used to check the presence of the specified file in the file system.

3. Based on the outcome of the exist? method, a corresponding message is printed to inform the user whether the file exists or not.


Comments