Skip to content

Ruby: Check whether a file or directory exists

Last updated on November 21, 2022

Checking whether a file exists or not, is one of the most basic file-related tasks which you will do most of the time, and thankfully Ruby’s File class provides two methods called File.file?(),File.exist?() to test file existence. The only difference between the two methods is, File.exist?() will also return true for directories.

The File.exist?() the function checks whether or not a file or directory exists. This function returns TRUE if the file or directory exists, otherwise, it returns FALSE.

#Ruby function to check directory or file existence
if(File.exist?('Hello.rb')) 
  puts 'file or directory exists'
else 
  puts 'file or directory not found'
end

The File.file?() function checks whether or not a file exists. This function returns TRUE if the file exists, otherwise, it returns FALSE.

#Ruby function to check file existence
if(File.file?('hello.rb')) 
    puts 'file exists'
else 
    puts 'file not found'
end

Apart from the above methods Ruby also provides File.directory?() method to check whether a directory exists or not. This function returns TRUE if the directory exists, otherwise, it returns FALSE.

#Ruby function to check directory existence
if(File.directory?('arjun')) 
  puts 'Directory exists'
else
  puts 'Directory not found'
end

As of now, you have seen a file and directory existence checking with Ruby’s File class methods, and thankfully Ruby’s Dir class also offers a method Dir.exist?() for checking directory existence. This function returns TRUE if the directory exists, otherwise, it returns FALSE.

#Ruby function to check directory existence
if(Dir.exist?('arjun')) 
  puts 'Directory exists'
else
  puts 'Directory not found'
end
0 0 votes
Article Rating
Subscribe
Notify of
guest

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments