{:test=...">

Why does clearing my hash also clear my hash array?

ruby-1.9.2-p180 :154 > a = []
 => []
ruby-1.9.2-p180 :154 > h = {:test => "test"}
 => {:test=>"test"} 
ruby-1.9.2-p180 :155 > a << h
 => [{:test=>"test"}] 
ruby-1.9.2-p180 :156 > h.clear
 => {} 
ruby-1.9.2-p180 :157 > a
 => [{}] 

I am very confused, especially since I can change the hash elements without affecting the array. But when I clear the hash, the array is updated and cleared of the contents of the hash. Can someone explain?

+3
source share
2 answers

When you execute a << h, you do pass the h link to a. Therefore, when you update h, they also see these changes because they contain a link, not a copy of this value.

So that it does not change in a, you must pass the cloned value of h to.

Example:

a << h.clone
+5
source

Ruby , - . , , , , .

-, , Ruby clone.

ruby-1.9.2-p136 :049 > h = { :test => 'foo' }
 => {:test=>"foo"}
ruby-1.9.2-p136 :050 > a = []
 => [] 
ruby-1.9.2-p136 :051 > a << h.clone
 => [{:test=>"foo"}] 
ruby-1.9.2-p136 :052 > h.clear
 => {} 
ruby-1.9.2-p136 :053 > a
 => [{:test=>"foo"}] 
+1

All Articles