Environment Variables in Crystal

Our first example demonstrates how to work with environment variables in Crystal. Environment variables are a universal mechanism for conveying configuration information to programs.

# 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.keys` to list all keys in the environment.
# Here we print all the keys.

puts
ENV.keys.each 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.

$ crystal run environment_variables.cr
FOO: 1
BAR: 

The list of keys in the environment will depend on your particular machine.

TERM_PROGRAM
PATH
SHELL
...
FOO

If we set BAR in the environment first, the running program picks that value up.

$ BAR=2 crystal run environment_variables.cr
FOO: 1
BAR: 2
...

In Crystal, environment variables are accessed through the ENV hash-like object. You can set variables using ENV["KEY"] = value, retrieve them with ENV["KEY"], and list all environment variables using ENV.keys. This provides a straightforward way to interact with the system’s environment variables.