277

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?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
iwan
  • 7,269
  • 18
  • 48
  • 66
  • 3
    Can you clarify if you want to know "whether it is a valid file path" or "whether it is a path to a file that exists"? – Paul Annesley Dec 21 '11 at 12:58
  • 5
    My advice is to spend 10 minutes reading all the methods in FileUtils and File classes. It will save you a lot of time in the long run! – Alain Dec 21 '11 at 12:54

2 Answers2

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

and

# Will also return true for directories - watch out!
File.exist?(filename)
Matt
  • 74,352
  • 26
  • 153
  • 180
zed_0xff
  • 32,417
  • 7
  • 53
  • 72
  • 14
    just File.file? should be enough, no? Docs: "Returns true if the named file exists and is a regular file" – Pavel K. Feb 26 '13 at 13:17
  • 1
    Important to note that the "and" above is not code: `File.exist?(filename) and File.file?(filename)` would always return false since File.exist? "Returns true if the named file is a directory, false otherwise." – Chris Hanson Mar 13 '14 at 22:06
  • 3
    Sorry chris you are wrong true and false => false ` >> File.file?('/etc/passwd') => true >> File.file?('/etc/') => false >> File.exists?('/etc/') => true >> File.exists?('/etc/passwd') => true >> File.file?('/etc/passwd') and File.exists?('/etc/passwd')` – shadowbq Apr 01 '14 at 17:41
  • exists? is now depreciated. – Mark Davies Sep 25 '17 at 10:34
  • @MarkDavies - Where ? https://ruby-doc.org/core-2.6.1/File.html which is the current version still valid there. – user3788685 Feb 14 '19 at 22:57
  • @user3788685: My comment was In response to "shadowbq" comment. They used an example of the "exists?" method and "exists?" is depreciated. However, "exist?" is current. – Mark Davies Feb 25 '19 at 08:58
  • 8
    @MarkDavies I don't mean to spam, but the word is deprecated. https://stackoverflow.com/questions/9208091/the-difference-between-deprecated-depreciated-and-obsolete – webdreamer Mar 26 '19 at 14:34
  • Yes you're right. – Mark Davies Mar 27 '19 at 15:35
67

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.

bill.lee
  • 2,207
  • 1
  • 20
  • 26
Paul Annesley
  • 3,387
  • 22
  • 23
  • 1
    thanks Paul, Pathname is what I needs. Somehow i am not able to find "File" and "FileTest" are accepting "FULL" path argument. Thanks again – iwan Jan 10 '12 at 04:45
  • Pathname is very useful but it's not a complete replacement for File and FileTest. It's easy to extend it so that it does have the same tests though, and then its utility as a wrapper really shines. – the Tin Man Dec 15 '16 at 17:36