The short answer is NO!, let's look more carefully at what's happening
to see why.
a = "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 # => 63930
b = a
# This binds b to the identical object to which a is currently bound so:
b.object_id # => 63930
b = "new value"
# We've now bound b to a different object.
b.object_id # => 63360
b # => "new value"
# But a is still bound to the first object
a.object_id # => 63930
# Now we re-bind b to the original object
b = a
b.object_id # => 63930
b # => "original object value"
# And send replace to that object.
b.replace("new value")
b.object_id # => 63930
b # => "new value"
a.object_id # => 63930
a # => "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 = "a new value"
b = "a new value"
a.object_id # => 60490
b.object_id # => 60420
# This illustrates that two strings with the same contents, aren't
necessarily the same object.
a == b # => true
a.equal?(b) # => false
# The == 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 = 1
b = 1
a.object_id # => 3
b.object_id # => 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.
···
On Sat, May 3, 2008 at 1:39 PM, Iñaki Baz Castillo <ibc@aliax.net> wrote:
Hi, using String#replace I can "simulate" a pointer (thanks to David A. for
the explanation):
a = "orignal a value"
b = a
b = "new value"
a
=> "original a value"
b
=> "new value"
This is obvious: after the new assigment of "b" it points to a different
object.
So I can use "replace":
a = "orignal a value"
b = a
b.replace "new value"
a
=> "new value"
b
=> "new value"
But Fixnum has not this method "replace", neither Float. Doesn't make sense
any primitive Ruby Class having this "replace" method instead of just one of
them?
-----
Rick DeNatale
My blog on Ruby
http://talklikeaduck.denhaven2.com/