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.
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
How do you share your great code without sharing your
Here it is with an environment variable:
# app.rb password = ENV['PASSWORD'] def my_method # do something with the password end
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
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
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.