How to Use Environment Variables in Ruby

09/20/2021

Contents

In this article, you will learn how to use environment variables in Ruby.

Using environment variables

Environment variables in Ruby are used to store data that can be accessed by any program running on the same system. They are useful for storing sensitive data like API keys, database credentials, and other configuration data that should not be hardcoded in the program.

To use environment variables in Ruby, you can follow these steps:

Set the environment variable

You can set an environment variable in your terminal using the export command followed by the variable name and its value. For example, to set an environment variable named API_KEY with a value of 12345, you can run the following command in your terminal:

export API_KEY=12345

Access the environment variable in Ruby

You can access the value of an environment variable in Ruby using the ENV global hash. The ENV hash contains all the environment variables defined in your system.

To access the value of the API_KEY environment variable we set earlier, you can use the following code:

api_key = ENV['API_KEY']

This will set the api_key variable to the value of the API_KEY environment variable.

Use the environment variable in your program

Once you have retrieved the value of the environment variable, you can use it in your program as needed. For example, you can use it to authenticate with an API service:

require 'net/http'

uri = URI('https://api.example.com')
params = { 'api_key' => api_key }

response = Net::HTTP.post_form(uri, params)

In this example, we are using the api_key variable to authenticate with an API service by passing it as a parameter in the request.