How to make Ruby variable that will evaluate to false in conditional expressions

元气小坏坏 提交于 2019-12-10 16:17:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!