How would I, say, determine if the file ~/.my_proj_config
exists on any OS in Ruby?
Asked
Active
Viewed 6,104 times
16

Phrogz
- 296,393
- 112
- 651
- 745

RyanScottLewis
- 13,396
- 16
- 56
- 84
4 Answers
21
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"))

Rob Di Marco
- 43,054
- 9
- 66
- 56
-
What version of ruby are you using? It is defined at http://ruby-doc.org/core-1.9.3/Dir.html#method-c-home – Rob Di Marco Jul 06 '12 at 21:15
3
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" )

Phrogz
- 296,393
- 112
- 651
- 745
0
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.

Rudi Visser
- 21,350
- 5
- 71
- 97
-
I was more wondering if '~' is an acceptable way to find the user's directory from any OS? – RyanScottLewis Apr 29 '11 at 11:17
-
Oh sorry, yes, the tilde has consistent behaviour cross-platform if you're using 1.9. See this commit to the codebase which adds functionality: http://redmine.ruby-lang.org/repositories/diff/ruby-19?rev=21312 – Rudi Visser Apr 29 '11 at 11:48
-
1Your statement appears not to be true. On Windows, using Ruby 1.9.2p180, I see: `File.exists?("~/tmp.rb")#=>false` but `File.exists?(File.join(Dir.home,'tmp.rb'))#=>true`. If you put in `File.expand_path` it works (see my answer). – Phrogz Apr 29 '11 at 15:56
-
Pathname#realpath does not do tilde (~) expansion. In fact, there's not a single instance of a tilde in the entire Pathname doc, which is disappointing, since it's supposed to be the new awesome. – odigity Nov 07 '15 at 01:36