Deep copy of arrays in Ruby

…衆ロ難τιáo~ 提交于 2019-11-30 01:59:30

问题


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.



来源:https://stackoverflow.com/questions/8607852/deep-copy-of-arrays-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!