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.
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 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.