1

I have a nested array of hashes and am trying to get a copy so that i can delete from the copy without it affecting the original.

However this fails. This is what i am trying.

a = [[some_hash1, some_hash2],[some_hash_3]]
b == a.dup
b[0].delete_at(0)

After this code is executed, some_hash1 is gone from a

2 Answers2

2

#dup produces a shallow copy of an object.

You could use marshalization:

a = [[{x: 2}, {y: 4}], [{z: 8}]]
b = Marshal.load(Marshal.dump(a))
b[0].delete_at(0)
puts a.to_s #=> [[{:x=>2}, {:y=>4}], [{:z=>8}]]
puts b.to_s #=> [[{:y=>4}], [{:z=>8}]]
Danil Speransky
  • 29,891
  • 5
  • 68
  • 79
0

If you are using Rails, you can use method deep_dup instead of Marshal.load,

$ a = [[{x: 2}, {y: 4}], [{z: 8}]]
$ # => [[{:x=>2}, {:y=>4}], [{:z=>8}]]
$ b = a.deep_dup
$ # => [[{:x=>2}, {:y=>4}], [{:z=>8}]]
$ b[0].delete_at(0)
$ #=> {:x=>2}
$ b
$ # => [[{:y=>4}], [{:z=>8}]]
$ a
$ # => [[{:x=>2}, {:y=>4}], [{:z=>8}]]

Of course, you have to use solution provided by @Danil if you are using only Ruby without Rails

Mohanraj
  • 4,056
  • 2
  • 22
  • 24