Ruby中数组的深拷贝 [英] Deep copy of arrays in Ruby
问题描述
我想在生产中获取一个对象,并对另一个相同类型的对象进行精确复制(复制其内容).我尝试从 ruby 控制台以 3 种方式执行此操作,但均未奏效:
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
我尝试的第三种方法是编组.
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
这篇关于Ruby中数组的深拷贝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!