Ruby: Most concise way to use an ENV variable if it exists, otherwise use default value
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.
The most reliable way for a general Hash is to ask if it has the key:
myvar = h.has_key?('MY_VAR') ? h['MY_VAR'] : 'default'
If you don't care about nil
or false
values (i.e. you want to treat them the same as "not there"), then undur_gongor's approach is good (this should also be fine when h
is ENV
):
myvar = h['MY_VAR'] || 'foobar'
And if you want to allow nil
to be in your Hash but pretend it isn't there (i.e. a nil
value is the same as "not there") while allowing a false
in your Hash:
myvar = h['MY_VAR'].nil? ? 'foobar' : h['MY_VAR']
In the end it really depends on your precise intent and you should choose the approach that matches your intent. The choice between if/else/end
and ? :
is, of course, a matter of taste and "concise" doesn't mean "least number of characters" so feel free to use a ternary or if
block as desired.
hash.fetch(key) { default_value }
Will return the value if it exists, and return default_value
if the key doesn't exist.