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}
<
First of all, the syntax for superators is
superator ":=" do |operand|
#code
end
It's a block, because superator is a metaprogramming macro.
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.
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)
Also, in your example, a
must first exist and be defined before being able to call the method :=
in it.
Your best bet is probably:
class Object
def deep_clone
Marshal::load(Marshal.dump(self))
end
end
to generate a deep clone of an object.
a = (b = {}).deep_clone
b[1] = 2
p a # => {}
p b # => {1=>2}