How to make Ruby variable that will evaluate to false in conditional expressions
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
# m开发者_开发知识库yproxy's backend object is not nil
else
# myproxy's backend object is nil
end
Any ideas?
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.
If you want that else
branch to be taken, then myproxy
must evaluate to either nil
or false
.
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#===
.
精彩评论