From: "Ara.T.Howard" Date: 2004-02-13T09:05:00+09:00 Subject: Re: Swapping out an instance between blinks On Thu, 12 Feb 2004, Gavin Kistner wrote: > Date: Thu, 12 Feb 2004 23:37:19 GMT > From: Gavin Kistner > Newsgroups: comp.lang.ruby > Subject: Swapping out an instance between blinks > > I'm writing a class (which I'm calling MutableTime) that is like a Time > object, but...well...mutable :) Changeable in all sorts of magical ways. > > I'd like it to have almost all the methods of Time, so this seems like a > clear case for inheritance: > > class MutableTime < Time > #... > end > > > However, I've run into cases where I want to modify some internal values > of the instance, and (since Time is written in C) I can't figure out > what private instance variables I may or may not have access to. > > For example, I want to let the user change the year: > > > class MutableTime < Time > def year=(newYear) > pieces = @t.to_a > pieces[5]=newYear > newTime = Time.local(*pieces) > self = newTime # ERROR > end > end > > Is there any way to, inside the method for an instance, magically swap > out that instance to be represented by a new instance? class MutableTime def initialize time = Time.now @time end def method_missing(meth, *args, &block) @time.send(meth, *args, &block) end def swap other @time = other end end also look at the delegate pattern in the oo library section of the pickaxe. > (I just realized that I can actually do what I want by making the newTime, > calculating the difference in seconds from the current time, and then adding > that in. Which is what I'll do, but I'm still interested in the answer to > the question above.) -a -- (short)