ruby - Why would changing a copied element in an array affect the original element? -


i tried add modified element in array:

mm = array.new mm.push({'a' => 1})   mm.unshift(mm[0]) mm[0]['b'] = 2 mm #=> [{'a' => 1, 'b' => 2}, {'a' => 1, 'b' => 2}] 

what expected was:

mm #=> [{'a' => 1, 'b' => 2}, {'a' => 1}] 

can tell me wrong?

you expect variables referenced value. in ruby, that’s not true. referenced reference. simplify,

▶ h = { a: 1 } #⇒ { :a => 1 } ▶ h_another_ref = h #⇒ { :a => 1 } ▶ h_another_ref[:b] = 42 ▶ h #⇒ { :a => 1, :b => 42 } 

here, both h , h_another_ref refer same object.

to achieve desired behaviour, might clone object (object#dup or object#clone):

▶ h = { a: 1 } #⇒ { :a => 1 } #                   ⇓⇓⇓⇓ ▶ h_another_inst = h.dup #⇒ { :a => 1 } ▶ h_another_inst[:b] = 42 ▶ h #⇒ { :a => 1 } ▶ h_another_inst #⇒ { :a => 1, :b => 42 } 

Comments