开发者

Checking if a file exists in the user's home directory

How would I, say开发者_开发知识库, determine if the file ~/.my_proj_config exists on any OS in Ruby?


A call to Dir.home is a OS independent way to get to the home directory for the user. You can then use it like

File.exists?(File.join(Dir.home, ".my_proj_config"))


This works in Ruby 1.9, but note that the call to expand_path is required on some systems (e.g. Windows):

File.exists?( File.expand_path "~/.my_proj_config" )


Use the class File and its method exist?.


Take a look at the Pathname class, specifically the realpath function - This will get you the full (expanded) path to your file.

http://www.ruby-doc.org/stdlib/libdoc/pathname/rdoc/classes/Pathname.html#M001991

You then use the File class along with exists? method to find out if that exists. You shouldn't need to use realpath if you use this method, however.

http://www.ruby-doc.org/core/classes/File.html#M000045

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜