A general way to replace an object in its own method
Using the lines you can do the following:
a = "hello"
a.upcase!
p a #=> "HELLO"
But how would I write my own method?
Something like (although this does not work explicitly):
class MyClass
def positify!
self = [0, self].max
end
end
I know there are some tricks that can be used in String, but what if I try to do something similar for 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