From: "David A. Black" Date: 2010-08-19T06:33:27+09:00 Subject: Re: Check existence of object and it's property at the same time 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.) -- David A. Black, Senior Developer, Cyrus Innovation Inc. The Ruby training with Black/Brown/McAnally Compleat Philadelphia, PA, October 1-2, 2010 Rubyist http://www.compleatrubyist.com