15

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.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
  • 1
    You're merely setting your variables in the first example. Try tt2.patients = tt.patiens.clone instead. – three Dec 22 '11 at 18:44

3 Answers3

19

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
BvuRVKyUVlViVIc7
  • 11,641
  • 9
  • 59
  • 111
Trip
  • 26,756
  • 46
  • 158
  • 277
6

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

@bar = @foo.clone

@bar.save

Community
  • 1
  • 1
BvuRVKyUVlViVIc7
  • 11,641
  • 9
  • 59
  • 111
2

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

ggorlen
  • 44,755
  • 7
  • 76
  • 106
tadman
  • 208,517
  • 23
  • 234
  • 262
  • 2
    Link doesn't work anymore. New link to [deep_clone is here](https://www.rubydoc.info/github/rubyworks/facets/Kernel:deep_clone). – user1934428 Aug 01 '18 at 08:00