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.

require 'English'

# To set a key/value pair, use ENV[key] = value. To get a
# value for a key, use ENV[key]. This will return
# nil if the key isn't present in the environment.
ENV['FOO'] = '1'
puts "FOO: #{ENV['FOO']}"
puts "BAR: #{ENV['BAR']}"

# Use ENV to access all key/value pairs in the
# environment. Here we print all the keys.
puts
ENV.each_key do |key|
  puts key
end

Running the program shows that we pick up the value for FOO that we set in the program, but that BAR is nil.

$ ruby environment_variables.rb
FOO: 1
BAR: 

TERM_PROGRAM
PATH
SHELL
...
FOO

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.

$ BAR=2 ruby environment_variables.rb
FOO: 1
BAR: 2
...

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.