From: Alex Stahl Date: 2010-08-19T06:21:44+09:00 Subject: Re: Check existence of object and it's property at the same time 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") && ... I'd be interested to learn why the first one short-circuits and the second doesn't. Anyone have any insight? Thanks, Alex On Wed, 2010-08-18 at 16:09 -0500, Cory Patterson wrote: > I run into this from time to time and I was wondering if there is a > cleaner way to do check that an object is not nil and also check a > property of that object. > > I want to do this: > > if !@member.nil? and @member.is_active? > ... do something ... > else > ... do something else ... > end > > But this obviously raises a no method error if @member is nil. > > I end up having to do: > > if !@member.nil? > if @member.is_active? > ... do something ... > else > ... do something else ... > end > end > > I know it isn't that much more verbose, but does ruby have a more > elegant way of handling this?