How to create an operator for deep copy/cloning of objects in Ruby?

后端 未结 2 1495
予麋鹿
予麋鹿 2021-01-07 10:06

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}
<         


        
2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-07 11:10

    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}
    

提交回复
热议问题