Ruby 中数组的深拷贝

发布于 2024-12-22 15:56:37 字数 786 浏览 5 评论 0原文

我想在生产中获取一个对象,并对另一个相同类型的对象进行精确的复制(复制其内容)。我尝试从 ruby​​ 控制台以 3 种方式执行此操作,但都不起作用:

  1. 假设您将 tt 作为要复制的第一个对象,tt2作为副本对象。我尝试的第一种方法是克隆数组

    tt2.患者 = tt.urls.患者
    tt2.doctors = tt.segments.doctors
    tt2.hospitals = tt.pixels.hospitals
    
  2. 我尝试的第二种方法是复制数组,这实际上与克隆数组相同:

    tt2.患者 = tt.患者.dup
    tt2.doctors = tt.doctors.dup
    tt2.hospitals = tt.hospitals.dup
    
  3. 我尝试的第三种方法是编组。

    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:

  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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

站稳脚跟 2024-12-29 15:56:37

简单的!

@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

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
辞慾 2024-12-29 15:56:37

这就是 ActiveRecord::Base#clone 方法的用途:

@bar = @foo.clone

@bar.save

This is what ActiveRecord::Base#clone method is for:

@bar = @foo.clone

@bar.save

柏拉图鍀咏恒 2024-12-29 15:56:37

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文