在它自己的方法中替换对象的通用方法 [英] Generic way to replace an object in it's own method

查看:36
本文介绍了在它自己的方法中替换对象的通用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于在它自己的方法中替换对象的通用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆