使用字符串可以做到这一点:
a = "hello"
a.upcase!
p a #=> "HELLO"
但我该如何编写自己的方法呢?
像这样的东西(虽然这显然不起作用):
class MyClass
def positify!
self = [0, self].max
end
end
我知道可以在 String 上使用一些技巧,但是如果我尝试对 Object 执行类似的操作该怎么办?
许多类是不可变的(例如Numeric
, Symbol
,...),因此没有方法允许您更改它们的值。
另一方面,任何Object
可以有实例变量并且可以修改它们。
有一种简单的方法可以将行为委托给已知对象(例如42
)并能够稍后更改为另一个对象,使用SimpleDelegator。在下面的例子中,quacks_like_an_int
行为就像Integer
:
require 'delegate'
quacks_like_an_int = SimpleDelegator.new(42)
quacks_like_an_int.round(-1) # => 40
quacks_like_an_int.__setobj__(666)
quacks_like_an_int.round(-1) # => 670
您也可以使用它来设计一个类,例如:
require 'delegate'
class MutableInteger < SimpleDelegator
def plus_plus!
__setobj__(self + 1)
self
end
def positify!
__setobj__(0) if self < 0
self
end
end
i = MutableInteger.new(-42)
i.plus_plus! # => -41
i.positify! # => 0
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)