KCM
KCM

Reputation: 49

ruby : can't understand memory address

when I study clone vs dup, I tried copy a object like below :

a = {'key1' => 1, 'key2' => {'key3' => 3, 'key4' => 4}}.freeze
b = a.clone
c = a.dup

a['key1'] = 32
# => RuntimeError: can't modify frozen Hash

b['key1'] = 32
# => RuntimeError: can't modify frozen Hash

c['key1'] = 32
# => 32

upper case result that, a and b value are share the memory but, when I check variable object_id, it returns different result :

a.object_id ## original
=> 70219554622880
b.object_id ## clone
=> 70219554589820

but in hash key object_id is same.

a['key1'].object_id ## original
=> 3
b['key1'].object_id ## clone
=> 3
c['key1'].object_id ## dup
=> 65

I don't understand a and b variable dosen't match object_id, but in hash key object_id is same.

Can you give me your thoughts, answers, or input? thanks.

Upvotes: 3

Views: 92

Answers (1)

Max
Max

Reputation: 22325

You might be confused specifically because you're using integers. Integers in Ruby are singletons: their integer value determines their object id.

x = 3
y = 3
x.object_id == y.object_id # true
x = "a"
y = "a"
x.object_id == y.object_id # false

However this is only true for integers up to a certain size.

x = 11111111111111111111111111111111
y = 11111111111111111111111111111111
x.object_id == y.object_id # false

This is because Ruby actually stores the integer value in the object id if it is small enough. If the number is too big it has to allocate a new object.

Upvotes: 5

Related Questions