Posted by Arjun on Friday 15th July 2016

Ruby - Check whether a file or directory exists

Ruby file exists directory exists File.exist?() File.directory?() Dir.exist?() File.File?()

Checking whether a file exists or not, is one of the most basic file related tasks which you will do most of the times and thankfully Ruby's File class provides two methods called File.file?(),File.exist?() to test file existence. The only difference between 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 offering 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