On unix platforms (linux, OS X, etc.), ENV["HOME"] , File.expandpath('~') or Dir.home all rely on the HOME environment variable. But sometimes you find that an environment variable is not set - this is common if you are working with a script run or with some package planners. If you are in this situation, you can get the correct home directory through:
require 'etc' Etc.getpwuid.dir
Having said that, since this question requires a cross-platform method, it should be noted that this will not work on Windows ( Etc.getpwuid will return nil there.) On Windows ENV["HOME"] and the methods mentioned above that rely on it , will work, despite the fact that the HOME variable will not be normally set on Windows - at startup Ruby will fill ENV["HOME"] based on the environment variables windows HOMEPATH and HOMEDRIVE . If the windows environment variables HOMEDRIVE and HOMEPATH not set, this will not work. I donโt know how common this actually is in Windows environments, and I donโt know any alternative that works in Windows.
Micah Dec 02 2018-12-12T00: 00Z
source share