From: Robert Klemme Date: 2004-04-22T17:09:07+09:00 Subject: Re: Creating bang methods "Gavin Kistner" schrieb im Newsbeitrag news:245541A6-93BD-11D8-A280-000A959CF5AC@refinery.com... > On Apr 21, 2004, at 11:34 AM, Jon Hurst wrote: > > [...] I would like to create bang methods of some math functions > > (mostly abs), but I don't know how to modify the reciever in place > > because the value of self cannot be changed. > > This problem bit me repeatedly. It's sort of a design feature, not a > flaw, as I understand it. > > Certain base classes are not meant to be mutable, per the design of the > language. The 'best' way to do this, I've been told, is what I did for > my MutableTime class, to wit: > a) Create a new class (that doesn't inherit from the other) > b) Keep your own instance variable that is the base class > c) When you need to modify the instance, swap out your instance, > otherwise > d) Pass method calls on to the instance. > > For example, something like > > class MyNumber > def initialize( initialValue=nil ) > @n = initialValue || 0 > end One check too much. > def abs! > @n = @n.abs > end > > def method_missing(meth, *args, &block) # :nodoc: > @n.send(meth, *args, &block) > end Those two can be combined. > end How about: class MyNumber def initialize( initialValue = 0 ) @n = initialValue end def method_missing(meth, *args, &block) if /\!$/ =~ meth.to_s @n = @n.send(meth.to_s[0...-1], *args, &block) else self.class.new @n.send(meth, *args, &block) end end # eql, == etc still missing here end x = MyNumber.new -10 p x x.abs! p x Regards robert