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\'], otherw
myvar = ENV['MY_VAR'].is_set? ? ENV['MY_VAR'] : 'foobar'
This way you keep the .is_set? method.
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.
The Demand gem which I wrote allows this to be extremely concise and DRY:
myvar = demand(ENV['MY_VAR'], 'foobar')
This will use ENV['MY_VAR']
only if it is present. That is, it will discard it just if it's nil, empty or a whitespace-only string, giving the default instead.
If a valid value for ENV['MY_VAR']
is falsy (such as false
), or an invalid value is truthy (such as ""
), then solutions like using ||
would not work.