From: Scott Gonyea Date: 2010-10-12T07:36:37+09:00 Subject: Re: more idiomatic way to avoid errors when calling method on variable that may be nil? Because I love dead horses (or just low productivity). Two more code examples: # Just get a String, rawr var = begin hash[key].to_s.downcase rescue NoMethodError "" end # Be a good citizen, and tread carefully var = case hash[key] when String then hash[key].downcase when Numeric then hash[key].to_s when Array then hash[key].join.downcase # rescue block for safety? when Hash then hash[key].values.join.downcase # rescue block for safety? else puts "LOOK AT WHAT YOU'VE DONE. YOU'VE MADE RUBY CRY." end On Mon, Oct 11, 2010 at 3:18 PM, Scott Gonyea wrote: > No! :(  Blanket rescue statements are not to be used.  It's a trivial > example, sure, but still. > > if hash.has_key?(:key) and hash[:key].is_a?(String) >  # do stuff > end > > Or, your rescue example... I'd at least rewrite it as: > > var = begin >        hash[key].downcase >      rescue NoMethodError >        nil >      end > > If you use Ruby Ketsup (aka, Active Support), you can put this everywhere: > > val = hash[key] if hash[key].present? > #or... > val = hash[key] unless hash[key].blank? > > So you know why you're rescuing here.  Blanket rescue foolishness can > and will cascade throughout your application.  Again, trivial > example...  But I think it shouldn't really be done in any > circumstance. > > Scott > > On Mon, Oct 11, 2010 at 1:17 PM, Kirk Haines wrote: >> On Mon, Oct 11, 2010 at 2:05 PM, Charles Calvert wrote: >>> I'm using Ruby 1.8.7 patchlevel 249 >>> >>> Is there a more idiomatic way to do the following? >>> >>> var = hash[key].nil? ? nil : hash[key].downcase >> >> I see nothing wrong with an explicit approach.  Here is an alternative, though: >> >> var = hash[key].downcase rescue nil >> >> >> Kirk Haines >> >> > >