Deep copy of arrays in Ruby

2020-03-01 06:49发布

问题:

I wanted to get an object on production and do an exact replica( copy over its contents) to another object of same type. I tried doing this in 3 ways from ruby console which none of them worked:

  1. Let's say you have the tt as the first object you want to copy over and tt2 as the replica object. The first approach I tried is cloning the array

    tt2.patients  = tt.urls.patients
    tt2.doctors   = tt.segments.doctors
    tt2.hospitals = tt.pixels.hospitals
    
  2. Second approach I tried is duplicating the array which is actually the same as cloning the array:

    tt2.patients  = tt.patients.dup
    tt2.doctors   = tt.doctors.dup
    tt2.hospitals = tt.hospitals.dup
    
  3. Third approach I tried is marhsalling.

    tt2.patients  = Marshal.load(Marshal.dump(tt.patients)) 
    tt2.doctors   = Marshal.load(Marshal.dump(tt.doctors)) 
    tt2.hospitals = Marshal.load(Marshal.dump(tt.hospitals)) 
    

None of the above works for deep copying from one array to another. After trying out each approach individually above, all the contents of the first object (tt) are nullified (patients, doctors and hospitals are gone). Do you have any other ideas on copying the contents of one object to another? Thanks.

回答1:

Easy!

@new_tt            = tt2.clone
@new_tt.patients   = tt2.patients.dup
@new_tt.doctors    = tt2.doctors.dup
@new_tt.hospitals  = tt2.hospitals.dup
@new_tt.save


回答2:

This is what ActiveRecord::Base#clone method is for:

@bar = @foo.clone

@bar.save



回答3:

Ruby Facets is a set of useful extensions to Ruby and has a deep_clone method that might work for you.