How to check for file existence

RubyFile

Ruby Problem Overview


Is there a Ruby class/method where I could pass "a full path", home/me/a_file.txt, to identify whether it is a valid file path?

Ruby Solutions


Solution 1 - Ruby

# file? will only return true for files
File.file?(filename)

and

# Will also return true for directories - watch out!
File.exist?(filename)

Solution 2 - Ruby

Check out Pathname and in particular Pathname#exist?.

File and its FileTest module are perhaps simpler/more direct, but I find Pathname a nicer interface in general.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioniwanView Question on Stackoverflow
Solution 1 - Rubyzed_0xffView Answer on Stackoverflow
Solution 2 - RubyPaul AnnesleyView Answer on Stackoverflow