如何在 Ruby 中创建对象的深层副本? [英] How to create a deep copy of an object in Ruby?

查看:40
本文介绍了如何在 Ruby 中创建对象的深层副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我进行了一些搜索,发现了一些关于创建深复制运算符的不同方法和帖子.

I did some searching found some different methods and posts about creating a deep copy operator.

在 Ruby 中是否有一种快速简便(内置)的方法来深度复制对象?这些字段不是数组或散列.

Is there a quick and easy (built-in) way to deep copy objects in Ruby? The fields are not arrays or hashes.

使用 Ruby 1.9.2.

Working in Ruby 1.9.2.

推荐答案

Deep Copy 没有内置在 vanilla Ruby 中,但您可以通过编组和解组对象来破解它:

Deep copy isn't built into vanilla Ruby, but you can hack it by marshalling and unmarshalling the object:

Marshal.load(Marshal.dump(@object))

但这并不完美,并且不适用于所有对象.更稳健的方法:

This isn't perfect though, and won't work for all objects. A more robust method:

class Object
  def deep_clone
    return @deep_cloning_obj if @deep_cloning
    @deep_cloning_obj = clone
    @deep_cloning_obj.instance_variables.each do |var|
      val = @deep_cloning_obj.instance_variable_get(var)
      begin
        @deep_cloning = true
        val = val.deep_clone
      rescue TypeError
        next
      ensure
        @deep_cloning = false
      end
      @deep_cloning_obj.instance_variable_set(var, val)
    end
    deep_cloning_obj = @deep_cloning_obj
    @deep_cloning_obj = nil
    deep_cloning_obj
  end
end

来源:

http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-list/43424

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

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