Devin Mullins
12/21/2005 2:11:00 PM
Hank Gong wrote:
>#integer
>
>
>#You can see that:
># 1) for the same integer, the object_id is the same
>
>
That's because Fixnums are "immediate." So are Symbols. It's a
performance thing. It also means, for example, you can't define
singleton methods on a Fixnum. Notice, actually, that you can decode the
integer value *from* the object-id, and vice versa.
># 2) When b change, a will not change
>
>
In Ruby, variables are *references* (a.k.a. pointers). You're just
telling b to reference a different object.
>#string
>
># 1) When you assign b=a, the object_id of b and a is same
># 2) but when you change b's string, the b's object_id will change
># 3) if you change b's string again, the b's object_id will also change
>
>
Strings, on the other hand, are not immediate. "Hello World".object_id
!= "Hello World".object_id -- each literal reference creates a new
String object. The #replace method Chintan mentioned, however, gets
around this, by wrapping the existing String object around a new string
-- and since a and b were originally pointing to the same object, a
would change with it.
>puts "For Array"
>a=[1,2,3,4]
>b=a
>puts a.object_id
>puts b.object_id
>b[2]=100
>puts b.object_id
>puts b.join(",")
>puts a.object_id
>puts a.join(",")
>
>
>
>>>For Array
>>>21563588
>>>21563588
>>>21563588
>>>1,2,100,4
>>>21563588
>>>1,2,100,4
>>>
>>>
># 1) when b=a, the b and a will be the same object_id
># 2) when you change b's elements, b's object_id will be same
># 3) when you change b's elements, a will also be changed
>
>
a and b are merely references to that one Array object, stored out in
voodoo land. The Array, itself, contains four references to other
objects. In this case, they were all Fixnums, and hence immediate (and
immutable), but try this out for size:
str = "my dog"
a=[1,2,3,4,str]
b=[:alpha, :omega, str]
str['dog'] = 'cat'
p a #=> [1, 2, 3, 4, "my cat"]
p b #=> [:alpha, :omega, "my cat"]
Both Arrays, while unique, reference the same String object, and so both
change at once. If, however, you did:
str = "my dog"
a=[1,2,3,4,str]
b=[:alpha, :omega, str]
str = 'my cat'
p a #=> [1, 2, 3, 4, "my dog"]
p b #=> [:alpha, :omega, "my dog"]
All you did was create a new String, "my cat", and point str to it. The
Arrays still point to the original "my dog" String.
>I think it's very interesting experiments. Hope someone can give us a clear
>explanation.
>
>
I hope that helped.
Devin