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

后端 未结 4 889
别跟我提以往
别跟我提以往 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 04:55

    Well, the upcase! method doesn't change the object identity, it only changes its internal structure (s.object_id == s.upcase!.object_id).

    On the other hand, numbers are immutable objects and therefore, you can't change their value without changing their identity. AFAIK, there's no way for an object to self-change its identity, but, of course, you may implement positify! method that changes properties of its object - and this would be an analogue of what upcase! does for strings.

提交回复
热议问题