Ruby – Check whether a file or directory exists

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 or directory existence, . Both the functions take file path as a parameter.

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

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

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.

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.

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

Arjun
I am Arjun from Hyderabad (India). I have been working as a software engineer from last 7+ years, and its my passion to learn new things and implement them as a practice. Aside from work, I likes gardening and spending time with pets.