阵列的深层副本在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:
-
假设你有
TT
只要你想拷贝过来的第一个对象和TT2
作为副本对象。我尝试的第一个方法是克隆阵列
Let's say you have the
tt
as the first object you want to copy over andtt2
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
第二条本办法我试过被复制数组实际上是一样的克隆数组:
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
第三种方法我试过被marhsalling。
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))
以上作品深度复制从一个阵列到另一个没有。尝试每一种方法单独之上,第一个对象的所有内容后( TT
)被废止(患者,医生和医院都没有了)。你对复制一个对象的内容到另一个任何其他的想法?谢谢你。
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.
轻松!
@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