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.
Asked
Active
Viewed 39 times
2 Answers
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
-
thanks, for my own knowledge can I ask what the difference is between a shallow copy and a deep copy? – alilland Sep 13 '16 at 16:57
-
@alilland Unlike shallow copy, deep copy will also copy any referenced objects in your data structure. – Paweł Duda Sep 13 '16 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.

B Seven
- 44,484
- 66
- 240
- 385