Ruby:使用 ENV 变量(如果存在)的最简洁方法,否则使用默认值

发布于 2024-12-08 09:25:29 字数 356 浏览 0 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

も让我眼熟你 2024-12-15 09:25:29
myvar = ENV['MY_VAR'] || 'foobar'

注意:这有点不正确(如果散列可以包含值nil),但由于ENV仅包含字符串,因此可能已经足够好了。

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.

染墨丶若流云 2024-12-15 09:25:29

对于一般哈希来说,最可靠的方法是询问它是否有密钥:

myvar = h.has_key?('MY_VAR') ? h['MY_VAR'] : 'default'

如果您不关心 nilfalse 值(即您想将它们视为与“不存在”相同),那么 undur_gongor 的方法很好(当 hENV 时这也应该没问题):

myvar = h['MY_VAR'] || 'foobar'

如果你想允许 nil< /code> 出现在你的哈希中,但假装它不存在(即 nil 值与“不存在”相同),同时在哈希中允许 false

myvar = h['MY_VAR'].nil? ? 'foobar' : h['MY_VAR']

最终,这实际上取决于您的精确值意图,您应该选择符合您意图的方法。 if/else/end之间的选择? : 当然,这是一个品味问题,“简洁”并不意味着“最少字符数”,因此可以根据需要随意使用三元或 if 块。

The most reliable way for a general Hash is to ask if it has the key:

myvar = h.has_key?('MY_VAR') ? h['MY_VAR'] : 'default'

If you don't care about nil or false 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 when h is ENV):

myvar = h['MY_VAR'] || 'foobar'

And if you want to allow nil to be in your Hash but pretend it isn't there (i.e. a nil value is the same as "not there") while allowing a false in your Hash:

myvar = h['MY_VAR'].nil? ? 'foobar' : h['MY_VAR']

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 or if block as desired.

终止放荡 2024-12-15 09:25:29
hash.fetch(key) { default_value }

如果存在则返回值,如果键不存在则返回default_value

hash.fetch(key) { default_value }

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

离不开的别离 2024-12-15 09:25:29

这最适合我:

ENV.fetch('VAR_NAME',"5445")

This works best for me:

ENV.fetch('VAR_NAME',"5445")
浅语花开 2024-12-15 09:25:29
myvar = ENV.fetch('MY_VAR') { 'foobar' }

如果未设置 ENV['MY_VAR'],则 'foobar' 为默认值。

myvar = ENV.fetch('MY_VAR') { 'foobar' }

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

神爱温柔 2024-12-15 09:25:29

尽管它与您给出的具体示例无关,因为您实际上是在询问哈希键而不是变量,但 Ruby 确实提供了一种检查变量定义的方法。使用 define? 关键字(它不是一个方法,而是一个关键字,因为它需要解释器的特殊处理),如下所示:

a = 1
defined? a
  #=> "local-variable"

@a = 2
defined? @a
  #=> "instance-variable"

@@a = 3
defined? @@a
  #=> "class-variable"

defined? blahblahblah
  #=> nil

因此你可以这样做:

var = defined?(var) ? var : "default value here"

据我所知,这是唯一的方法而不是用丑陋的 begin/rescue/end 块按照您要求的方式定义变量,而不会冒 NameError 的风险。正如我所说,这不适用于哈希,因为:

hash = {?a => 2, ?b => 3}
defined? hash[?c]
  #=> "method"

即您正在检查方法 [] 是否已定义,而不是您使用它访问的键/值对。

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.

扶醉桌前 2024-12-15 09:25:29

另一种可能的替代方案,即使 ENV['MY_VAR'] 结果是一个假值,它也会起作用

myvar  = ENV['MY_VAR'].presence || 'foobar'

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

myvar  = ENV['MY_VAR'].presence || 'foobar'
千年*琉璃梦 2024-12-15 09:25:29

我编写的 Demand gem 允许它变得非常简洁和干燥:

myvar = demand(ENV['MY_VAR'], 'foobar')

这将使用ENV['MY_VAR'] 仅当它存在时。也就是说,如果它是 nil、空或只有空格的字符串,它就会丢弃它,并给出默认值。

如果 ENV['MY_VAR'] 的有效值为假(例如 false),或者无效值为真(例如 ""),那么使用 || 之类的解决方案将不起作用。

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.

黑白记忆 2024-12-15 09:25:29

我是 Ruby 新手,发布我在 2021 年找到的答案,也许对某人有用。

检查 env key 是否存在:

 include?(name) → true or false
 has_key?(name) → true or false
 member?(name) → true or false
 key?(name) → true or false

获取默认值的 env:

 ENV.fetch(name, :default_val)

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:

 include?(name) → true or false
 has_key?(name) → true or false
 member?(name) → true or false
 key?(name) → true or false

get env with default value:

 ENV.fetch(name, :default_val)

ref: https://docs.ruby-lang.org/en/master/ENV.html

逐鹿 2024-12-15 09:25:29

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文