ruby 引用、dup VS rails deep_dup

ruby

引用 vs dup

a = b = {a: 1}
b.delete_if{|k, v| v==1}
a # => {}
a.object_id == b.object_id # => true

a = (b =  {a: 1}).dup
b.delete_if{|k, v| v==1}
a # => {:a=>1}
a.object_id == b.object_id # => false

dup vs deep_dup

# ruby dup
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

# 这意味着

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

b['key2']['key5']  # =>5

# rails deep_dup

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

# 这意味着

a['key2']['key5'] = 5
b['key2']['key5']  # => nil

发表于 2019.02.25