Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deep copy of arrays in Ruby

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.

like image 374
Sait Mesutcan Ilhaner Avatar asked Dec 22 '11 17:12

Sait Mesutcan Ilhaner


People also ask

How do you copy an array in Ruby?

Ruby does provide two methods for making copies of objects, including one that can be made to do deep copies. The Object#dup method will make a shallow copy of an object. To achieve this, the dup method will call the initialize_copy method of that class.

What is a deep copy of an array?

A deep copy of an object is a copy whose properties do not share the same references (point to the same underlying values) as those of the source object from which the copy was made.

Is arrays copy of a deep copy?

It is a deep copy. It appears shallow in the case of Strings because under the covers, Strings are Singletons.

What is Deep_dup?

The #deep_dup method in Rails method returns true . This means that an instance that contains the Object class in its ancestor chain is eligible to deep copy.


3 Answers

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
like image 68
Trip Avatar answered Oct 18 '22 05:10

Trip


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

@bar = @foo.clone

@bar.save

like image 32
BvuRVKyUVlViVIc7 Avatar answered Oct 18 '22 03:10

BvuRVKyUVlViVIc7


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

like image 2
tadman Avatar answered Oct 18 '22 05:10

tadman