I'd like to add something like a callback function to a Ruby array, so that when elements are added to that array, this function is called. One thing I can think of is to override all methods (like <<, =, insert, ...) and call that callback from there.
Is there an easier solution?
Use the "Observer" pattern to be notified of changes in the size of the array you wish to observer: Ruby Observer This saves you from having to override all methods that add an element to the array
The following code only invokes the
size_changed
hook when the array size has changed and it is passed the new size of the array:You should probably create your own class that wraps array. You don't want to override a core class with a callback like you are describing, not only does that make the code brittle but it becomes less expressive for future developers who may not be expecting Array to make a callback.