Topic: How to copy Hash or Array straight?

i am having Problems with the following duplicate Issue

# i fill some XML File into "doc"
doc = REXML::Document.new( xml_data )
# i parse the Doc via DOM parsing
doc.elements.each("Tree/Item") { |element1|
        array1 = []
        ## collect Items to an Array ##
        element1.elements.each("ChildsOfItem") { |el1| array1  << el1.text }
        ## store Item Name and Childs as Array in my_hash ##
        my_hash1.store(element1.elements["ItemName"].text, array1)
      }

# making a copy of my_hash
doc.elements.each("Tree/Item") { |element2|
        array2 = []
        ## once again I collect the Items ##
        element2.elements.each("ChildsOfItem") { |el2| array2 << el2.text }
       ## and once again i store Item Name and Childs as Array in my_hash ##
       my_hash2.store(element2.elements["ItemName"].text, array2)
      }

### And here is my Problem ###
# when I try to change the Array Items in my_hash2, i also get the Array Items in my_hash1 changed !!!
my_hash2.each { |key, array|
        array.each { |Item|   Item.replace(attr_hash[attrib])
        }
      }

# my_hash1 is also affected ...

how can i change my_hash2 without loosing values in my_hash1 ?
i tried to *.clone   *.dup without success so far.

Any Ideas?
Greetings, Michael

Last edited by pango (2010-06-01 09:09:33)

Re: How to copy Hash or Array straight?

any ideas?

Re: How to copy Hash or Array straight?

Probably a bit late to be of help but for anyone else here's one way

new_hash = Marshal.load(Marshal.dump(original_hash))