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

后端 未结 9 1077
小鲜肉
小鲜肉 2020-12-23 08:59

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         


        
相关标签:
9条回答
  • 2020-12-23 09:22
    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-23 09:25
    hash.fetch(key) { default_value }
    

    Will return the value if it exists, and return default_value if the key doesn't exist.

    0 讨论(0)
  • 2020-12-23 09:30
    myvar = ENV.fetch('MY_VAR') { 'foobar' }
    

    'foobar' being the default if ENV['MY_VAR'] is unset.

    0 讨论(0)
  • 2020-12-23 09:35

    Another possible alternative, which will work even if ENV['MY_VAR'] turnsout to be a false value

    myvar  = ENV['MY_VAR'].presence || 'foobar'
    
    0 讨论(0)
  • 2020-12-23 09:39

    This works best for me:

    ENV.fetch('VAR_NAME',"5445")
    
    0 讨论(0)
提交回复
热议问题