On Feb 25, 2009, at 12:11 PM, I=F1aki Baz Castillo wrote:

> Hi, is it correct the following "rescue" usage?
>
> myvar =3D 1  # Fixnum
> othervar =3D myvar.downcase rescue myvar
> =3D> 1
>
> It seems to work, but is it really correct? Thanks.
>
> -- =20
> I=F1aki Baz Castillo
> <ibc / aliax.net>


Hmm, "correct"? Well, it is certainly legal syntax and is equivalent to:

othervar =3D begin
              myvar.downcase
            rescue
              myvar
            end

But, it might not be the best way to shave the yak.

othervar =3D myvar.respond_to?(:downcase) ? myvar.downcase : myvar

might perform better if the exception to be rescued is expensive to =20
construct only to then be thrown away.  (I don't know if there's any =20
special optimization of the expression form of rescue compared to the =20=

block form.)

It also can hide problems that you won't know that you have. For =20
example,
   myvar =3D nil
   othervar =3D myvar.downcase rescue myvar
Did you want to set othervar to nil also?
Perhaps you need othervar as a downcased String? Maybe it would be =20
better as:
   othervar =3D myvar.to_s.downcase

In any case, you'd have to decide.

-Rob


Rob Biedenharn		http://agileconsultingllc.com
Rob / AgileConsultingLLC.com=