Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Most concise way to use an ENV variable if it exists, otherwise use default value

Tags:

ruby

hash

In Ruby, I am trying to write a line that uses a variable if it has been set, otherwise default to some value:

myvar = # assign it to ENV['MY_VAR'], otherwise assign it to 'foobar' 

I could write this code like this:

if ENV['MY_VAR'].is_set? #whatever the function is to check if has been set   myvar = ENV['MY_VAR'] else   myvar = 'foobar' end 

But this is rather verbose, and I'm trying to write it in the most concise way possible. How can I do this?

like image 506
Andrew Avatar asked Oct 05 '11 18:10

Andrew


People also ask

How do I use an environment variable in Ruby?

Passing Environment Variables to Ruby To pass environment variables to Ruby, simply set that environment variable in the shell. This varies slightly between operating systems, but the concepts remain the same. To set an environment variable on the Windows command prompt, use the set command.

Should you use .ENV in production?

Using environment variables is a somewhat common practice during Development but it is actually not a healthy practice to use with Production. While there are several reasons for this, one of the main reasons is that using environment variables can cause unexpected persistence of variable values.

Can I use variables in .ENV file?

The . env file contains the individual user environment variables that override the variables set in the /etc/environment file. You can customize your environment variables as desired by modifying your . env file.


1 Answers

myvar = ENV['MY_VAR'] || 'foobar' 

N.B. This is slightly incorrect (if the hash can contain the value nil) but since ENV contains just strings it is probably good enough.

like image 157
undur_gongor Avatar answered Sep 17 '22 13:09

undur_gongor