RyanScottLewis
RyanScottLewis

Reputation: 14016

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?

Upvotes: 16

Views: 6203

Answers (4)

Phrogz
Phrogz

Reputation: 303224

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" )

Upvotes: 3

Rob Di Marco
Rob Di Marco

Reputation: 44952

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"))

Upvotes: 21

Rudi Visser
Rudi Visser

Reputation: 21979

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

Upvotes: 0

evnu
evnu

Reputation: 6680

Use the class File and its method exist?.

Upvotes: 0

Related Questions