Iñaki Baz Castillo
5/3/2008 6:42:00 PM
El S=E1bado, 3 de Mayo de 2008, Rick DeNatale escribi=F3:
> The short answer is NO!, let's look more carefully at what's happening
> to see why.
>
> a =3D "original object value"
> # This binds the variable a to a string object. The identity of the
> # string object can be obtained using the object_id method
>
> a.object_id # =3D> 63930
>
> b =3D a
>
> # This binds b to the identical object to which a is currently bound so:
>
> b.object_id # =3D> 63930
>
> b =3D "new value"
> # We've now bound b to a different object.
> b.object_id # =3D> 63360
> b # =3D> "new value"
>
> # But a is still bound to the first object
> a.object_id # =3D> 63930
>
> # Now we re-bind b to the original object
> b =3D a
> b.object_id # =3D> 63930
> b # =3D> "original object value"
>
> # And send replace to that object.
> b.replace("new value")
> b.object_id # =3D> 63930
> b # =3D> "new value"
> a.object_id # =3D> 63930
> a # =3D> "new value"
>
> # Two points. First, methods (like object_id, and replace) operate on
> objects, NOT variables.
> # Second, the replace method causes the string to change its contents,
> NOT its identity. Some Ruby
> # objects are mutable, they have methods which can alter their state,
> other objects are immutable, once
> # created they can't be changed.
>
> a =3D "a new value"
> b =3D "a new value"
> a.object_id # =3D> 60490
> b.object_id # =3D> 60420
>
> # This illustrates that two strings with the same contents, aren't
> necessarily the same object.
> a =3D=3D b # =3D> true
> a.equal?(b) # =3D> false
>
> # The =3D=3D method compares state, equal? compares identity.
>
> # Some objects, such as Fixnums, Symbols, nil, true, and false have
> only one instance for a
> # particular state.
>
> a =3D 1
> b =3D 1
> a.object_id # =3D> 3
> b.object_id # =3D> 3
>
> Such objects certainly need to be immutable. If there's only one
> instance of the fixnum 42, then you really wouldn't want to change its
> value to say 43, or life, the universe, and everything would lose
> their meaning.
I hope explanations like this would appear in some Ruby manual and so :)
=2D-=20
I=F1aki Baz Castillo