Environment Variables in Ruby
Environment variables are a universal mechanism for conveying configuration information to Unix programs. Let’s look at how to set, get, and list environment variables.
Running the program shows that we pick up the value for FOO
that we set in the program, but that BAR
is nil.
The list of keys in the environment will depend on your particular machine.
If we set BAR
in the environment first, the running program picks that value up.
In Ruby, environment variables are accessed through the ENV
hash. This provides a simple interface to read and write environment variables. The ENV
object behaves like a hash, allowing you to get and set values using the standard square bracket notation.
When reading an environment variable that doesn’t exist, Ruby returns nil
instead of an empty string. This can be useful for checking if an environment variable is set.
To list all environment variables, you can use ENV.each_key
or ENV.each_pair
if you need both keys and values. This provides a Ruby-idiomatic way to iterate over all environment variables.
Remember that changes to ENV
in a Ruby program only affect the environment of the current process and its child processes. They do not modify the system environment permanently.