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?
How to check for file existence [duplicate]
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! –
Fernald
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"? –
Caltanissetta
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.
thanks Paul, Pathname is what I needs. Somehow i am not able to find "File" and "FileTest" are accepting "FULL" path argument. Thanks again –
Vacuous
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. –
Reiterate
# file? will only return true for files
File.file?(filename)
and
# Will also return true for directories - watch out!
File.exist?(filename)
just File.file? should be enough, no? Docs: "Returns true if the named file exists and is a regular file" –
Pepe
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." –
Seidule 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')` –
Emergency
exists? is now depreciated. –
Agape
@MarkDavies - Where ? ruby-doc.org/core-2.6.1/File.html which is the current version still valid there. –
Amitosis
@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. –
Agape
@MarkDavies I don't mean to spam, but the word is deprecated. #9208591 –
Sunshine
Yes you're right. –
Agape
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.
thanks Paul, Pathname is what I needs. Somehow i am not able to find "File" and "FileTest" are accepting "FULL" path argument. Thanks again –
Vacuous
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. –
Reiterate
© 2022 - 2024 — McMap. All rights reserved.