From: Alex Stahl Date: 2010-08-19T06:52:44+09:00 Subject: Re: Check existence of object and it's property at the same time Strange... it was failing before (like a few weeks ago) w/ a NoMethodError on has_key? when it wasn't a hash. But trying it again now works fine as you note. On Wed, 2010-08-18 at 16:33 -0500, David A. Black wrote: > On Thu, 19 Aug 2010, David A. Black wrote: > > > Hi -- > > > > On Thu, 19 Aug 2010, Alex Stahl wrote: > > > >> I've run into a similar situation before, and found that > >> short-circuiting in an 'if' statement is inconsistent. > >> > >> For instance, this will short-circuit and prevent evaluation of > >> subsequent statements if the first one is false (which is desired > >> obviously): > >> > >> unless creds.class.to_s =~ /Hash/ && creds.has_key?("user") && ... > >> > >> > >> But this won't: > >> > >> unless creds.instance_of?(Hash) && creds.has_key?("user") && ... > > > > They both short-circuit. Note that the puts("here") statement never gets > > executed. > > > >>> creds = {} > > => {} > >>> unless creds.class.to_s =~ /Hash/ && creds.has_key?("user") && > >>> puts("here"); 1; end > > => 1 > >>> unless creds.instance_of?(Hash) && creds.has_key?("user") && puts("here"); > >>> 1; end > > => 1 > > (P.S. I've made the second condition fail, rather than the first, but if > you make creds a non-hash it will short-circuit after the first one.) >