如何在Ruby中创建对象的深层副本? [英] How to create a deep copy of an object in Ruby?
本文介绍了如何在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.
推荐答案
深度副本不是内置到香草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屋!
查看全文