Ruby:使用 ENV 变量(如果存在)的最简洁方法,否则使用默认值
在 Ruby 中,我试图编写一行,如果已设置变量,则使用该变量,否则默认为某个值:
myvar = # assign it to ENV['MY_VAR'], otherwise assign it to 'foobar'
我可以这样编写此代码:
if ENV['MY_VAR'].is_set? #whatever the function is to check if has been set
myvar = ENV['MY_VAR']
else
myvar = 'foobar'
end
但这相当冗长,我试图将其写在最简洁的方式可能。我该怎么做?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
注意:这有点不正确(如果散列可以包含值
nil
),但由于ENV
仅包含字符串,因此可能已经足够好了。N.B. This is slightly incorrect (if the hash can contain the value
nil
) but sinceENV
contains just strings it is probably good enough.对于一般哈希来说,最可靠的方法是询问它是否有密钥:
如果您不关心
nil
或false
值(即您想将它们视为与“不存在”相同),那么 undur_gongor 的方法很好(当h
为ENV
时这也应该没问题):如果你想允许
nil< /code> 出现在你的哈希中,但假装它不存在(即
nil
值与“不存在”相同),同时在哈希中允许false
:最终,这实际上取决于您的精确值意图,您应该选择符合您意图的方法。
if/else/end
和之间的选择? :
当然,这是一个品味问题,“简洁”并不意味着“最少字符数”,因此可以根据需要随意使用三元或if
块。The most reliable way for a general Hash is to ask if it has the key:
If you don't care about
nil
orfalse
values (i.e. you want to treat them the same as "not there"), then undur_gongor's approach is good (this should also be fine whenh
isENV
):And if you want to allow
nil
to be in your Hash but pretend it isn't there (i.e. anil
value is the same as "not there") while allowing afalse
in your Hash:In the end it really depends on your precise intent and you should choose the approach that matches your intent. The choice between
if/else/end
and? :
is, of course, a matter of taste and "concise" doesn't mean "least number of characters" so feel free to use a ternary orif
block as desired.如果存在则返回值,如果键不存在则返回
default_value
。Will return the value if it exists, and return
default_value
if the key doesn't exist.这最适合我:
This works best for me:
如果未设置
ENV['MY_VAR']
,则'foobar'
为默认值。'foobar'
being the default ifENV['MY_VAR']
is unset.尽管它与您给出的具体示例无关,因为您实际上是在询问哈希键而不是变量,但 Ruby 确实提供了一种检查变量定义的方法。使用
define?
关键字(它不是一个方法,而是一个关键字,因为它需要解释器的特殊处理),如下所示:因此你可以这样做:
据我所知,这是唯一的方法而不是用丑陋的
begin
/rescue
/end
块按照您要求的方式定义变量,而不会冒 NameError 的风险。正如我所说,这不适用于哈希,因为:即您正在检查方法
[]
是否已定义,而不是您使用它访问的键/值对。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:Hence you could do:
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:i.e. you're checking that the method
[]
is defined rather than the key/value pair you're using it to access.另一种可能的替代方案,即使 ENV['MY_VAR'] 结果是一个假值,它也会起作用
Another possible alternative, which will work even if ENV['MY_VAR'] turnsout to be a false value
我编写的 Demand gem 允许它变得非常简洁和干燥:
这将使用
ENV['MY_VAR']
仅当它存在时。也就是说,如果它是 nil、空或只有空格的字符串,它就会丢弃它,并给出默认值。如果
ENV['MY_VAR']
的有效值为假(例如false
),或者无效值为真(例如""
),那么使用||
之类的解决方案将不起作用。The Demand gem which I wrote allows this to be extremely concise and DRY:
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 asfalse
), or an invalid value is truthy (such as""
), then solutions like using||
would not work.我是 Ruby 新手,发布我在 2021 年找到的答案,也许对某人有用。
检查 env key 是否存在:
获取默认值的 env:
ref: https:// docs.ruby-lang.org/en/master/ENV.html
I am new guy to Ruby, post the answer I found at 2021, maybe useful for someone.
check if env key exists:
get env with default value:
ref: https://docs.ruby-lang.org/en/master/ENV.html
myvar = ENV['MY_VAR'].is_set? ? ENV['MY_VAR'] : 'foobar'
这样你就可以保留 .is_set 了吗?方法。
myvar = ENV['MY_VAR'].is_set? ? ENV['MY_VAR'] : 'foobar'
This way you keep the .is_set? method.