From: Robert Klemme Date: 2007-10-01T23:02:19+09:00 Subject: Re: canonical Array#append to hang hook 2007/9/30, Rassat Nicolas : > I have a class which inherit from Array. I want to perform some task > each time something is append to an instance of this class. The problem > is: there are so many way to append something to an array. For example: > > class Narray < Array > alias_method :old_push, :push > def push(*obj) > p "pushing #{obj}" > old_push(*obj) > end > alias_method :old_append, :<< > def <<(obj) > p "< old_append(obj) > end > alias_method :old_bracket, :[]= > def []=(i,l=0) > p "[]=ing #{i}" > old_bracket(i,l) > end > alias_method :old_add, :+ > def +(i) > p "+ing #{i}" > old_add(i) > end > end > > a = Narray.new > a.push(1) > a << 2 > a[a.length] = 3 > a = a + [4] > p a > > I forgot Array#insert, Array#fill and probably other... > > Is there any Array#append function that can hooked to perform task every > time something is append to a? > > Any solution is welcome. I'd probably consider not using inheritance but wrapping your Array in some other class. That way you can expose the interface you want to expose and esp. limit the way to modify the array. Kind regards robert