2012-12-06 29 views
1

我遇到了一個問題,我無法在克隆哈希中替換字符串而不影響其原始內容。我最好用一個例子來解釋:在Ruby中使用克隆哈希上的gsub修改原來的

product_attributes = raw_attributes.clone 

# do some stuff on product_attributes like removing hash elements using "select!" 

puts product_attributes[:code] 
# => 64020-001 
puts raw_attributes[:code] 
# => 64020-001 

product_attributes[:code].gsub!(/[\/|\-][0-9\.]*$/, "") 

puts product_attributes[:code] 
# => 64020 
puts raw_attributes[:code] 
# => 64020 

我在OSX上使用Ruby 1.9.3p327。

這是一個已知問題(或甚至功能)?或者我做錯了什麼?

+1

的[?如何複製在Ruby中的散列(可能重複http://stackoverflow.com/questions/4157399/how- do-i-copy-a-hash-in-ruby) –

回答

3

clone只做了數組的淺拷貝,所以元素被複制而不是克隆自己。請參閱What's the most efficient way to deep copy an object in Ruby?以瞭解如何高效地進行深層複製的一些優秀討論。

如果你只需要深克隆這個值:

product_attributes = raw_attributes.clone 
product_attributes[:code] = product_attributes[:code].clone 
+0

哦,這確實有道理。謝謝。 我做了很有戲劇性的標題:)我最好去讀一本書。 –