Cross-platform means of getting user's home directory in Ruby?

With Ruby 1.9 and above you can use Dir.home.


The File.expand_path method uses the Unix convention of treating the tilde (~) specially, so that ~ refers to the current user's home directory and ~foo refers to foo's home directory.

I don't know if there's a better or more idiomatic way, but File.expand_path('~') should get you going.


ENV["HOME"] or ENV["HOMEPATH"] should give you what you want.

homes = ["HOME", "HOMEPATH"]

realHome = homes.detect {|h| ENV[h] != nil}

if not realHome
   puts "Could not find home directory"
end