Showing posts with label ruby clone. Show all posts
Showing posts with label ruby clone. Show all posts

Thursday, January 16, 2014

Ruby clone, dup vs Rails deep_dup

In Ruby:

dup and clone only duplicates the main object and leaves the inner object same.

for example

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

a.object_id == b.object_id # false

a['key2'].object_id == b['key2'].object_id #true


This means if i do something like

a['key2']['key5'] = 5

it will also add in b
b['key2']['key5']  # 5

In Rails:

for example

a= {'key1' => 1, 'key2' => {'key3' => 3, 'key4' => 4}}
b = a.deep_dup

a.object_id == b.object_id # false

a['key2'].object_id == b['key2'].object_id #false


This means if i do something like

a['key2']['key5'] = 5

it will not added in b
b['key2']['key5']  # nil