Ruby:使用ENV变量(如果存在)的最简洁方法,否则使用默认值 [英] Ruby: Most concise way to use an ENV variable if it exists, otherwise use default value
本文介绍了Ruby:使用ENV变量(如果存在)的最简洁方法,否则使用默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Ruby中,我试图编写一条使用变量的行(如果已设置),否则默认为某个值:
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'], otherwise assign it to 'foobar'
我可以这样编写这段代码:
I could write this code like this:
if ENV['MY_VAR'].is_set? #whatever the function is to check if has been set
myvar = ENV['MY_VAR']
else
myvar = 'foobar'
end
但是这很冗长,我正在尝试以最简洁的方式编写它.我该怎么办?
But this is rather verbose, and I'm trying to write it in the most concise way possible. How can I do this?
推荐答案
myvar = ENV['MY_VAR'] || 'foobar'
这有点不正确(如果散列可以包含值nil
),但是由于ENV
仅包含字符串,因此可能就足够了.
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.
这篇关于Ruby:使用ENV变量(如果存在)的最简洁方法,否则使用默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文