0

I have a hash with an object id of 19475160, I need to clone my hash, how would I go about doing this? Every google search and article I have found points me to rails solutions but I cant find anything that is a regular ruby solution.

alilland
  • 1,370
  • 1
  • 16
  • 32

2 Answers2

1

This will do a shallow copy of an object:

 obj2 = obj.clone

This will do a deep copy of an object:

  obj2 = Marshal.load(Marshal.dump(obj))
Paweł Duda
  • 1,683
  • 3
  • 18
  • 35
0

You can use dup.

h = {a:1}
h2 = h.dup
h[:a] = 2
h2
=> {:a=>1}

h and h2 have different object_id's.

From dup reference:

Produces a shallow copy of obj—the instance variables of obj are copied, but not the objects they reference.

B Seven
  • 42,103
  • 65
  • 226
  • 370