Ruby Basics : Setting Environment variables


To learn about setting environment variables in your projects.


Step 1

You can set the environment variable in a terminal like this:

$export JUNK='test'

Step 2

In irb, you can read the value like this:


Step 3

Don't check for nil for the existence of environment variables.


Step 4

Check for the existence of the key in ENV hash like this:


Step 5

This makes your conditionals in yml files easier to read. So instead of doing this:

ENV['JUNK'].nil?? ENV['JUNK'] : 'dev'

You can do:

ENV.has_key?('JUNK')? ENV['JUNK'] : 'dev'

This also prevents nil exceptions in your code.

Step 6

Setting environment variable values in a terminal will only last for that session. If you want to set it permanently for your production VPS, you need to add :

export SECRET_API_KEY='very secret'

to the ~/.profile file.


In this article you learned how to set environment variables properly in your projects.

Related Articles

Software Compatibility Best Practices

I spoke to some of the most talented and experienced software developers. I have created a guide that is filled with valuable insights and actionable ideas to boost developer productivity.

You will gain a better understanding of what's working well for other developers and how they address the software compatibility problems.

Get the Guide Now