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 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.

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.

0 0 votes
Article Rating
Subscribe
Notify of
guest
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Kevin W. Carpenter
Kevin W. Carpenter
3 years ago

I can’t tell when this was posted, but the purpose of File.file? and File.directory? are very different from what you posted here.

File.file? checks that the file exists **and is a file**. It will return false if passed in the path to a directory.
File.directory? checks that the directory exists **and is a directory or a symlink to a directory**.

References:
https://ruby-doc.org/core-2.2.0/File.html#method-c-file-3F
https://ruby-doc.org/core-2.2.0/File.html#method-c-directory-3F

DMCA.com Protection Status
2
0
Would love your thoughts, please comment.x
()
x