This is quite a quick question. I currently use*
do_this if (testvar ||= false)
Which works just fine.
But this approach unnerves me because while fast, it does not short-circuit like defined?(testvar) && testvar
does, and it instantiates and assigns a value to a local variable that is subsequently never used, which seems inefficient.
I enjoy the very reasonable fact that instance variables are nil before assignment, but I'd like for the situation to be just as easy for local variables.
EDIT: * – t开发者_运维问答hat's a huge lie. I don't know why I said that. I don't use testvar ||= false
. That would be silly. What I have used, however, is testvar rescue false
, which doesn't have nearly as many ugly side effects (does it?).
I don't know about a "fancy" way but there's an explicit way, which is sometimes better than fancy, IMHO.
do_this if defined? testvar and testvar
How about:
do_this unless testvar.nil?
精彩评论