How to Check If a File Exists in Ruby?

here simple Checking whether a ruby check if file exists or not, is one of the most basic file related project which you will do often How to Delete a File in Ruby? and thankfully Ruby’s File class supports two methods called File.file?() and File.exist?() to simple test file existence. The only main this two methods difference between two ways is File.exist?() will also return only Boolean value like as a true for directories.

Ruby – Check whether a file or directory exists

The File.exist?() the function checks whether or not a file or folder exists. This function returns only Boolean value like as a TRUE if the file or folder exists, otherwise, it returns FALSE.

Also Read This πŸ‘‰   How to Delete a File in Ruby?

check directory or file existence

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

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

check file existence

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

Also Read: How to Delete a File in Ruby?

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

Also Read This πŸ‘‰   How to Delete a File in Ruby?

check directory existence

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

As of now, you have seen a file and folder existence checking with Ruby’s File class ways as well as thankfully Ruby’s Dir class also offering method Dir.exist?() for checking folder existence. This function returns only Boolean value like as a TRUE if the folder exists, otherwise, it returns FALSE.

check directory existence

#Ruby function to check folder existence
if(Dir.exist?('pakainfo')) 
  puts 'folder exists'
else
  puts 'folder not found'
end