From: Stephen White Date: 2001-01-19T00:51:55+09:00 Subject: [ruby-talk:9520] Enhancing the functionality of an object I have a OOP programming problem. 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? In my imaginary application, the sum is going to be looked up a lot more than the list is going to be changed. My first thought would be "have an instance veriable to keep the sum". So I want to write something like: class SumArray < Array attr_read :sum def initialize *args @sum = 0 super args end def []= index, value @sum += value - self[index] super index, value end end (no idea if the above is even near correct, I haven't used classes in Ruby much) This is nice and clean, doesn't require any knowledge of how Array is implemented, and provides the additional call "sum" which returns the cached value, as the calculation is performed only when changing the list. 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. Would I have to write a mirror class that intercepts all the places the values could be changed, like the initial value of an array, out of range array extensions, iterators, etc? -- steve@deaf.org