Ruby 中数组的深拷贝
我想在生产中获取一个对象,并对另一个相同类型的对象进行精确的复制(复制其内容)。我尝试从 ruby 控制台以 3 种方式执行此操作,但都不起作用:
假设您将
tt
作为要复制的第一个对象,tt2
作为副本对象。我尝试的第一种方法是克隆数组tt2.患者 = tt.urls.患者 tt2.doctors = tt.segments.doctors tt2.hospitals = tt.pixels.hospitals
我尝试的第二种方法是复制数组,这实际上与克隆数组相同:
tt2.患者 = tt.患者.dup tt2.doctors = tt.doctors.dup tt2.hospitals = tt.hospitals.dup
我尝试的第三种方法是编组。
tt2.患者 = Marshal.load(Marshal.dump(tt.患者)) tt2.doctors = Marshal.load(Marshal.dump(tt.doctors)) tt2.hospitals = Marshal.load(Marshal.dump(tt.hospitals))
上述方法都不适用于从一个数组到另一个数组的深度复制。分别尝试上述每种方法后,第一个对象 (tt
) 的所有内容都无效(患者、医生和医院都消失了)。您对于将一个对象的内容复制到另一个对象还有其他想法吗?谢谢。
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:
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 arraytt2.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))
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
简单的!
Easy!
这就是 ActiveRecord::Base#clone 方法的用途:
This is what ActiveRecord::Base#clone method is for:
Ruby Facets 是一组有用的 Ruby 扩展,并具有 deep_clone 方法可能适合您。
Ruby Facets is a set of useful extensions to Ruby and has a deep_clone method that might work for you.