Generic way to replace an object in it's own method

后端 未结 4 849
别跟我提以往
别跟我提以往 2021-01-13 04:51

With strings one can do this:

a = \"hello\"
a.upcase!
p a #=> \"HELLO\"

But how would I write my own method like that?

Somethin

4条回答
  •  花落未央
    2021-01-13 05:09

    You cannot change self to point to anything other than its current object. You can make changes to instance variables, such as in the case string which is changing the underlying characters to upper case.

    As pointed out in this answer: Ruby and modifying self for a Float instance

    There is a trick mentioned here that is a work around, which is to write you class as a wrapper around the other object. Then your wrapper class can replace the wrapped object at will. I'm hesitant on saying this is a good idea though.

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题