With strings one can do this:
a = \"hello\"
a.upcase!
p a #=> \"HELLO\"
But how would I write my own method like that?
Somethin
Many classes are immutable (e.g. Numeric
, Symbol
, ...), so have no method allowing you to change their value.
On the other hand, any Object
can have instance variables and these can be modified.
There is an easy way to delegate the behavior to a known object (say 42
) and be able to change, later on, to another object, using SimpleDelegator. In the example below, quacks_like_an_int
behaves like an 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
You can use it to design a class too, for example:
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