阵列的深层副本在Ruby中 [英] Deep copy of arrays in Ruby

查看:123
本文介绍了阵列的深层副本在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:


  1. 假设你有 TT 只要你想拷贝过来的第一个对象和 TT2 作为副本对象。我尝试的第一个方法是克隆阵列

  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


  • 第二条本办法我试过被复制数组实际上是一样的克隆数组:

  • 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
    

    这篇关于阵列的深层副本在Ruby中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆