How to Check If a File Exists in Ruby

09/22/2021

Contents

In this article, you will learn how to check if a file exists in Ruby.

Checking if a file exists

In Ruby, you can check if a file exists using several methods. Here are a few approaches that you can use to check if a file exists in Ruby:

Using the File.exist? method

The File.exist? method returns true if a file exists and false otherwise. Here’s an example:

if File.exist?("path/to/file.txt")
  puts "File exists"
else
  puts "File does not exist"
end

Using the File.file? method

The File.file? method returns true if a file exists and is a regular file (not a directory or a symbolic link) and false otherwise. Here’s an example:

if File.file?("path/to/file.txt")
  puts "File exists"
else
  puts "File does not exist"
end

Using the FileTest.exist? method

The FileTest.exist? method is an alias for the File.exist? method and works the same way. Here’s an example:

if FileTest.exist?("path/to/file.txt")
  puts "File exists"
else
  puts "File does not exist"
end

Using the Dir.glob method

The Dir.glob method returns an array of file names that match a pattern. If the array is not empty, it means that the file exists. Here’s an example:

if Dir.glob("path/to/file.txt").any?
  puts "File exists"
else
  puts "File does not exist"
end

Using the FileUtils.compare_file method

The FileUtils.compare_file method compares the contents of two files and returns true if they are identical. You can use this method to check if a file exists by comparing it to an empty file. Here’s an example:

require 'fileutils'

if FileUtils.compare_file("path/to/file.txt", "/dev/null")
  puts "File exists"
else
  puts "File does not exist"
end

Note that the above methods only check if a file exists. If you also need to check if a file is readable, writable, or executable, you can use the File.readable?, File.writable?, and File.executable? methods, respectively.