From: jstern@... (Josh Stern) Date: 2001-01-19T06:40:02+09:00 Subject: [ruby-talk:9524] Re: Enhancing the functionality of an object Stephen White wrote: >Imagine I have to keep the sum of a list of numbers. I'd think "list of >numbers, use an array". Now how could I make the Array class keep a sum >of all its elements? >[..] > def []= index, value > @sum += value - self[index] >[..] >The problem is that just defining the []= operator wouldn't be enough. >There isn't a single point in which a value gets set in an Array, so I >have no place I can put a hook into when a value gets changed. You can keep index variables that indicate the valid range of indices for the current array, and you maintain the invariant that every value within that range is originally initialized to zero. If your intended usage doesn't really look like a pretty continous range, you would want to use a dictionary anyway. -= Josh