如何使Ruby变量在条件表达式中评估为false [英] How to make Ruby variable that will evaluate to false in conditional expressions
问题描述
在条件语句中使用变量时,我想使变量(代理对象)的值为假。我知道我可以使用.nil吗?甚至var == nil,但我认为这还不够好。我正在尝试做的是:
I want to make my variable (a proxy object) evaluate to false when used in conditional sentences. I know I can use .nil? and even var == nil but I think that's not good enough. What I am trying go do is to:
if myproxy # not only myprroxy.nil? or myproxy == nil, but just that
# myproxy's backend object is not nil
else
# myproxy's backend object is nil
end
有什么想法吗?
推荐答案
仅有的两个在Ruby的布尔值上下文中计算为假值的对象是 nil
, NilClass
的单例实例和 false
, FalseClass
的单例实例。 每个其他对象的计算结果都为真值。
The only two objects that evaluate to a false-ish value in a boolean context in Ruby are nil
, the singleton instance of NilClass
and false
, the singleton instance of FalseClass
. Every other object evaluates to a tru-ish value.
如果您想要 else
要采用的分支,然后 myproxy
必须评估为 nil
或 false
。
If you want that else
branch to be taken, then myproxy
must evaluate to either nil
or false
.
如果您想要布尔型的东西,您可以对其进行实际控制,则可以尝试使用 case
表达式并覆盖大小写包含运算符 MyProxy#===
。
If you want something boolean-ish that you have actual control over, you could try a case
expression and override the case subsumption operator MyProxy#===
.
这篇关于如何使Ruby变量在条件表达式中评估为false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!