如何在 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