在它自己的方法中替换对象的通用方法

在它自己的方法中替换对象的通用方法

问题描述:

使用字符串可以做到这一点:

With strings one can do this:

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

但是我该如何编写自己的方法呢?

But how would I write my own method like that?

类似的东西(虽然这显然不起作用):

Something like (although that doesn't work obviously):

class MyClass
  def positify!
    self = [0, self].max
  end
end

我知道可以在 String 上使用一些技巧,但是如果我想为 Object 做这样的事情怎么办?

I know there are some tricks one can use on String but what if I'm trying to do something like this for Object?

好吧,upcase! 方法不会改变对象标识,它只会改变其内部结构(s.object_id == s.upcase!.object_id).

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

另一方面,数字是不可变的对象,因此,您无法在不更改身份的情况下更改其值.AFAIK,对象无法自行更改其身份,但是,当然,您可以实现 positify! 方法来更改其对象的属性 - this 会是什么 upcase 的类比!用于字符串.

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.