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

后端 未结 9 1079
小鲜肉
小鲜肉 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:48

    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.

提交回复
热议问题