Ruby:如果存在变量,则使用最简洁的方式,否则使用默认值 [英] Ruby: Most concise way to use a variable if it exists, otherwise use default value
本文介绍了Ruby:如果存在变量,则使用最简洁的方式,否则使用默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
myvar =#赋值给ENV ['MY_VAR'],否则赋值给'foobar'
<如果ENV ['MY_VAR']。is_set
#w函数检查是否已设置
myvar = ENV ['MY_VAR']
else
myvar ='foobar'
end
但是这是比较冗长的,我试图用最简洁的方式写出来。我怎样才能做到这一点?
解决方案
myvar = ENV ['MY_VAR'] || 'foobar'
N.B。这有点不正确(如果哈希值可以包含值 nil
),但由于 ENV
只包含字符串,它可能是好的够了。
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'
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:如果存在变量,则使用最简洁的方式,否则使用默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文