On Thu, Aug 12, 2010 at 2:38 AM, Ralph Shnelvar <ralphs / dos32.com> wrote:
> David,
>
>>> That's great and solves my particular problem.
>
>>> But what if the class being derived from does not have a replace method?
>
> DAB> If the object has state that can be modified, then there will be (by
> DAB> definition) ways to modify that state. If it doesn't, then there won't
> DAB> be, and the class in question is probably a bad starting point if you
> DAB> want to create objects with state that can be modified.
>
> DAB> That's one of the advantages of using proxy objects and delegators: you
> DAB> gain an extra axis along which you can make decisions about things like
> DAB> object state. Even though you can't change (say) a Fixnum, you can
> DAB> create objects with integer attributes that *can* be changed.
>
> Could you expand on this with an example, please?

irb(main):001:0> require 'delegate'
=> true
irb(main):002:0> class MutableFixnum < Delegator
irb(main):003:1> def initialize i
irb(main):004:2> super
irb(main):005:2> @value = i
irb(main):006:2> end
irb(main):007:1> def __getobj__
irb(main):008:2> @value
irb(main):009:2> end
irb(main):014:1> def __setobj__ value
irb(main):015:2> @value = value
irb(main):016:2> end
irb(main):017:1> def add! x
irb(main):018:2> __setobj__(__getobj__ + x)
irb(main):019:2> end
irb(main):020:1> end
=> nil
irb(main):021:0> a = MutableFixnum.new 1
=> 1
irb(main):022:0> a + 3
=> 4
irb(main):023:0> a.add! 3
=> 4
irb(main):024:0> a
=> 4

Jesus.