开发者

Why does clearing my hash, also clear my array of hashes?

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'm very confused, especially since I can 开发者_如何学Gochange the elements of the hash without it affecting the array. But when I clear the hash the array is updated and cleared of its hash contents. Can someone explain?


When you do a << h, you are really passing the reference of h to a. So when you update h, a also see's those changes because it contains a reference rather than a copy of that value.

In order for it not to change in a, you must pass a cloned value of h into a.

An example would be:

a << h.clone


Ruby does not make a copy of this hash when you add it to the array — it simply stores a reference to the original variable. So, when you empty the original variable, the reference stored in the array now refers to the empty hash.

If you want to copy the hash element so this does not occur, use Ruby's clone method.

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"}] 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜