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
  • 2,039
  • 1
  • 21
  • 42

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,713
  • 4
  • 18
  • 36
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
  • 44,484
  • 66
  • 240
  • 385