How to Use the Ruby exist? Method

09/26/2021

Contents

In this article, you will learn how to use the Ruby exist? method.

Using the exist? method

The exist? method in Ruby is a built-in method used to check if a file or a directory exists in the file system. It returns true if the file or directory exists, and false otherwise.

To use the exist? method, you need to specify the file or directory path as an argument to the method. For example, to check if a file named “example.txt” exists in the current directory, you can use the following code:

if File.exist?("example.txt")
  puts "File exists"
else
  puts "File does not exist"
end

In this example, the File.exist? method is used to check if the “example.txt” file exists in the current directory. If the file exists, the program prints “File exists”. Otherwise, it prints “File does not exist”.

You can also use the exist? method with a full file path, like this:

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

This code checks if the file “example.txt” exists in the directory specified by the full path “/path/to”.

The exist? method can also be used to check if a directory exists. For example:

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

This code checks if the directory “/path/to/directory” exists. If the directory exists, the program prints “Directory exists”. Otherwise, it prints “Directory does not exist”.

You can also use the exist? method with a relative path, like this:

This code checks if the directory “subdirectory” exists inside the “directory” directory in the current working directory. If the directory exists, the program prints “Directory exists”. Otherwise, it prints “Directory does not exist”.