DEV Community

Cover image for 49 Days of Ruby: Day 15 - Environment Variables
Ben Greenberg
Ben Greenberg

Posted on

49 Days of Ruby: Day 15 - Environment Variables

Welcome to day 15 of the 49 Days of Ruby! 🎉

Today we are discussing the concept of environment variables. These become very important when you want to build a program that has sensitive data, among other use cases.

Let's say you are building an app that has a password embedded in the code. You probably do not want to widely share that password with everyone who sees the code, so what do you do?

Environment variables can offer a solution.

Environment variables let you supply a keyword as the value for the password that gets replaced with the actual value during runtime.

Let's take a look at an example.

Environment Variables in Ruby

Suppose we had an app called app.rb. This app needs a password in the code:

# app.rb

password = "super_secret_password"

def my_method
  # do something with the password
end
Enter fullscreen mode Exit fullscreen mode

How do you share your great code without sharing your super_secret_password?

Here it is with an environment variable:

# app.rb

password = ENV['PASSWORD']

def my_method
  # do something with the password
end
Enter fullscreen mode Exit fullscreen mode

Do you see the difference?

The first half specifies it is an environment variable: ENV. The second half inside the brackets is the name of the specific environment variable, PASSWORD in our example.

How do create an environment variable? We'll see later on different Ruby tooling to manage environment variables. For now, we'll show how to define an environment variable from the command line.

Let's say you wanted to run your app.rb file from the command line. You would execute: ruby app.rb and the program would run. To add the password as the environment variable you would preface that command with the following:

$ PASSWORD=my_secret_password ruby app.rb
Enter fullscreen mode Exit fullscreen mode

You can create environment variables and define them at runtime by adding them to your execution from the command line like above. You can even have multiple ones:

$ VARIABLE_1=something VARIABLE_2=something_else VARIABLE_3=another_thing ruby app.rb
Enter fullscreen mode Exit fullscreen mode

What do you think about environment variables? What might you use them for? Share your learning!

Come back tomorrow for the next installment of 49 Days of Ruby! You can join the conversation on Twitter with the hashtag #49daysofruby.

Top comments (0)