Because I love dead horses (or just low productivity). Two more code exampl=
es:

# Just get a String, rawr
var =3D begin
        hash[key].to_s.downcase
      rescue NoMethodError
        ""
      end

# Be a good citizen, and tread carefully
var =3D 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 <scott / aitrus.org> wrote:
> No! :( =A0Blanket rescue statements are not to be used. =A0It's a trivial
> example, sure, but still.
>
> if hash.has_key?(:key) and hash[:key].is_a?(String)
> =A0# do stuff
> end
>
> Or, your rescue example... I'd at least rewrite it as:
>
> var =3D begin
> =A0 =A0 =A0 =A0hash[key].downcase
> =A0 =A0 =A0rescue NoMethodError
> =A0 =A0 =A0 =A0nil
> =A0 =A0 =A0end
>
> If you use Ruby Ketsup (aka, Active Support), you can put this everywhere=
:
>
> val =3D hash[key] if hash[key].present?
> #or...
> val =3D hash[key] unless hash[key].blank?
>
> So you know why you're rescuing here. =A0Blanket rescue foolishness can
> and will cascade throughout your application. =A0Again, trivial
> example... =A0But I think it shouldn't really be done in any
> circumstance.
>
> Scott
>
> On Mon, Oct 11, 2010 at 1:17 PM, Kirk Haines <wyhaines / gmail.com> wrote:
>> On Mon, Oct 11, 2010 at 2:05 PM, Charles Calvert <cbciv / yahoo.com> wrote=
:
>>> I'm using Ruby 1.8.7 patchlevel 249
>>>
>>> Is there a more idiomatic way to do the following?
>>>
>>> var =3D hash[key].nil? ? nil : hash[key].downcase
>>
>> I see nothing wrong with an explicit approach. =A0Here is an alternative=
, though:
>>
>> var =3D hash[key].downcase rescue nil
>>
>>
>> Kirk Haines
>>
>>
>
>