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

后端 未结 9 1107
小鲜肉
小鲜肉 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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.

提交回复
热议问题