ruby check if exists
Ruby: Check if a File Exists
To check if a file exists in Ruby, you can use the File.exist?
method. Here are the steps to do this:
- Use the
File.exist?
Method: - The
File.exist?
method returnstrue
if the file exists andfalse
if it doesn't. Example:
ruby if File.exist?('path_to_file') puts 'File exists' else puts 'File does not exist' end
Example Usage:
Suppose you want to check if a file named "example.txt" exists in the current directory:
ruby if File.exist?('example.txt') puts 'File exists' else puts 'File does not exist' end
Explanation of the Code:
- In this example, the
File.exist?('example.txt')
method is used to check if the file "example.txt" exists in the current directory. - If the file exists, it will output "File exists"; otherwise, it will output "File does not exist".
By using the File.exist?
method, you can easily check for the existence of a file in Ruby.