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

后端 未结 2 1498
予麋鹿
予麋鹿 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:05

    wow, superators look neat! But unfortunately, this won't work for you, for two reasons. First, your operator does not match the regex (you cannot use a colon). Easy enough, find a new operator. But the second one I don't think can be overcome, the superator is basically a method name defined on the object to the left. So you can't use it for assignment statements. If your variable is not defined, then you cannot use it, that would raise an error. And if it is defined, then you can't change its type in any way that is obvious to me (maybe with some level of reflection and metaprogramming that is way beyond anything I know, but it honestly seems unlikely... of course, I would have never expected it to be possible to create superators, so who knows).

    So I think you're back to hacking parse.y and rebuilding your Ruby.

提交回复
热议问题