如何在Ruby中创建用于对象的深层复制/克隆的运算符? [英] How to create an operator for deep copy/cloning of objects in Ruby?
问题描述
我想通过引入一个新的运算符(例如:=
)来实现以下目标
I would like to achieve the following by introducing a new operator (e.g. :=
)
a := b = {}
b[1] = 2
p a # => {}
p b # => {1=>2}
据我了解,我需要修改Object
类,但是我不知道该怎么做才能得到我想要的东西.
As far as I understand, I need to modify the Object
class, but I don't know what to do in order to get what I want.
require 'superators'
class Object
superator ":=" operand # update, must be: superator ":=" do |operand|
# self = Marshal.load(Marshal.dump(operand)) # ???
end
end
您能帮我吗?
更新
好吧,超级管理员可能不会在这里帮助我,但我仍然想要这样的操作员.我(或您)如何为Ruby创建扩展,可以将其作为模块加载?
Ok, superators will probably not help me here, but I still want such operator. How can I (or you) create an extension for Ruby, which I could load as a module?
require 'deep_copy_operator'
a !?= b = {} # I would prefer ":=" but don't really care how it is spelled
b[1] = 2
p a # => {}
p b # => {1=>2}
推荐答案
首先,超级符号的语法为
First of all, the syntax for superators is
superator ":=" do |operand|
#code
end
这是一个块,因为超级程序是一个元编程宏.
It's a block, because superator is a metaprogramming macro.
第二,您在Marshal
上做了一些事情...但是有点魔术.只要您完全了解自己在做什么,就可以随意使用它.
Secondly, you have something going their with Marshal
...but it's a bit of magic-ish. Feel free to use it as long as you understand exactly what it is you're doing.
第三,您在做的事情对超级操作器来说不太可行(我相信),因为在功能中不能修改self
. (如果其他人知道,请告诉我)
Thirdly, what you are doing isn't quite doable with a superator (I believe), because self
cannot be modified during a function. (if someone knows otherwise, please let me know)
另外,在您的示例中,a
必须首先存在并且已定义,然后才能在其中调用方法:=
.
Also, in your example, a
must first exist and be defined before being able to call the method :=
in it.
您最好的选择可能是:
class Object
def deep_clone
Marshal::load(Marshal.dump(self))
end
end
生成对象的深层克隆.
a = (b = {}).deep_clone
b[1] = 2
p a # => {}
p b # => {1=>2}
这篇关于如何在Ruby中创建用于对象的深层复制/克隆的运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!