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.

2

2 Answers 2

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))
2
  • thanks, for my own knowledge can I ask what the difference is between a shallow copy and a deep copy?
    – alilland
    Sep 13, 2016 at 16:57
  • @alilland Unlike shallow copy, deep copy will also copy any referenced objects in your data structure. Sep 13, 2016 at 17:19
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.