Ruby provides the ENV object for easy access to a variety of environment variables. ENV is not actually a hash, but you access individual values like you would a hash:
If you need to, you can convert it into a Hash using the to_hash method, so to see a complete list of keys and values stored in ENV, you could do this:
ENV.to_hash.each do |key, value|
Many of these values you may never use, but a few are worth noting...
HOMEDRIVE returns the home drive, for example:
ENV['HOMEDRIVE'] # returns "C:"
APPDATA returns the path to the Application Data folder(ie, "C:")
ENV['APPDATA'] # returns "C:\Documents and Settings\Joe DiMaggio\Application Data"
USERPROFILE returns the user's home directory:
ENV['USERPROFILE'] # returns "C:\Documents and Settings\Joe DiMaggio"
USERNAME returns the Windows user's name or Windows login:
ENV['USERNAME'] # returns "Joe DiMaggio"
ProgramFiles returns the path to the Program Files folder:
ENV['ProgramFiles] # returns "C:\Program Files"
windir returns the path to the Program Files folder:
ENV['windir'] # returns "C:\Windows"
Writing to Environment Variables
To quote The Pickaxe:
"A Ruby program may write to the ENV object, which on most systems changes the values of the corresponding environment variables. However, this change is local to the process that makes it and to any subsequently spawned child processes. This inheritance of environment variables is illustrated in the code that follows. A subprocess changes an environment variable and this change is seen in a process that it then starts. However, the change is not visible to the original parent. (This just goes to prove that parents never really know what their children are doing.)"
A tip of the hat to reader Revence, who shared a code snippet that utilized the ENV object, reminding me of its value.
That's all for now. As always, leave a comment here or via email if you have questions or suggestions for future topics.
Thanks for stopping by!