Ruby中数组的深层副本
我想在生产中获得一个对象并做一个精确的副本(复制其内容)到另一个相同类型的对象。 我尝试从ruby控制台以3种方式执行此操作,但它们都没有工作:
-
假设您将
tt
作为要复制的第一个对象,将tt2
作为副本对象。 我尝试的第一种方法是克隆数组tt2.patients = tt.urls.patients tt2.doctors = tt.segments.doctors tt2.hospitals = tt.pixels.hospitals
-
我尝试的第二种方法是复制数组,这实际上与克隆数组相同:
tt2.patients = tt.patients.dup tt2.doctors = tt.doctors.dup tt2.hospitals = tt.hospitals.dup
-
我尝试的第三种方法是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))
以上都不适用于从一个arrays到另一个arrays的深度复制。 在上面单独尝试每种方法之后,第一个对象( tt
)的所有内容都无效(患者,医生和医院都消失了)。 您是否有任何其他想法将一个对象的内容复制到另一个对象? 谢谢。
简单!
@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
这就是ActiveRecord :: Base#clone方法的用途:
@bar = @ foo.clone
@ bar.save
Ruby Facets是一组对Ruby有用的扩展,并且有一个可能适合您的deep_clone方法。