From: "Iñaki Baz Castillo" Date: 2008-05-04T03:41:50+09:00 Subject: Re: Why there is not "replace" method for Fixnum? El Sábado, 3 de Mayo de 2008, Rick DeNatale escribió: > 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. I hope explanations like this would appear in some Ruby manual and so :) -- Iñaki Baz Castillo