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'] || '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.
Although it's not relevant in the specific example you gave since you're really asking about hash keys, not variables, Ruby does give a way to check variable definition. Use the defined?
keyword (it's not a method, but a keyword since it needs special handling by the interpreter), like so:
a = 1
defined? a
#=> "local-variable"
@a = 2
defined? @a
#=> "instance-variable"
@@a = 3
defined? @@a
#=> "class-variable"
defined? blahblahblah
#=> nil
Hence you could do:
var = defined?(var) ? var : "default value here"
As far as I know, that's the only way other than an ugly begin
/rescue
/end
block to define a variable in the way that you ask without risking a NameError. As I said, this doesn't apply to hashes since:
hash = {?a => 2, ?b => 3}
defined? hash[?c]
#=> "method"
i.e. you're checking that the method []
is defined rather than the key/value pair you're using it to access.
hash.fetch(key) { default_value }
Will return the value if it exists, and return default_value
if the key doesn't exist.
myvar = ENV.fetch('MY_VAR') { 'foobar' }
'foobar'
being the default if ENV['MY_VAR']
is unset.
Another possible alternative, which will work even if ENV['MY_VAR'] turnsout to be a false value
myvar = ENV['MY_VAR'].presence || 'foobar'
This works best for me:
ENV.fetch('VAR_NAME',"5445")