Hi,
Am Dienstag, 22. Dez 2009, 09:57:28 +0900 schrieb Sonja Elen Kisa:
Constants are variables:
=A0X =3D "hello"
=A0X =3D "bye" =A0 =A0 =A0 =A0 =A0 =A0 # not allowed (just a warning)
=A0X.replace "bye" =A0 =A0 =A0 # this is allowed!
=A0X.freeze
=A0X.replace "hi again" =A0# forbidden (TypeError)
But you can also freeze other variables:
=A0x =3D "foo"
=A0x.freeze
=A0x.replace "bar" =A0 =A0 =A0 # forbidden (TypeError)
No you can't freeze variables, you can freeze the objects they reference.
ruby-1.8.7-p174 > x =3D 'foo'
=3D> "foo"
ruby-1.8.7-p174 > x.freeze
=3D> "foo"
ruby-1.8.7-p174 > x =3D 'boo'
=3D> "boo"
ruby-1.8.7-p174 > A =3D 'bar'
=3D> "bar"
ruby-1.8.7-p174 > A.freeze
=3D> "bar"
ruby-1.8.7-p174 > A =3D 'baz'
(irb):6: warning: already initialized constant A
=3D> "baz"
ruby-1.8.7-p174 > A
=3D> "baz"
Variables in Ruby are not objects, nor do they contain objects, they
refer to objects. Object#freeze prevents future changes to the state
of an object, no matter how it is referenced, and it does nothing to
prevent the (re)binding of variables.
And as for warnings vs. errors. IMHO, warnings are just that,
warnings. They warn of something which might be, and sometimes
usually will be a problem, but not always. In most cases, the
response should be to do whatever need be done to eliminate them, but
sometimes they are warnings in the sense of "fasten your seatbelt" or
"slippery when wet." Redefining a "Constant" can be useful as times.
And some time warnings, like "parenthesize argument(s) for future
version", turn out to be non-warnings when the envisioned future
version (of the Ruby parser) is abandoned.
--=20
Rick DeNatale
Blog:
http://talklikeaduck.denhaven2.com/
Twitter:
http://twitter.com/RickDeNatale
WWR:
http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn:
http://www.linkedin.com/in/rickdenatale