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

Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.