问题
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
Any ideas?
回答1:
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#===.
来源:https://stackoverflow.com/questions/2152979/how-to-make-ruby-variable-that-will-evaluate-to-false-in-conditional-expressions