From: Gavin Sinclair Date: 2003-01-13T16:38:03+09:00 Subject: Re: Array_Of(AClass) On Monday, January 13, 2003, 5:37:21 PM, Tom wrote: > i wonder, a coding challenge of sorts, what would it talk to create an > Array_Of(AClass) constructor? such that an array would be created that can > only contain objects of the class specified. Sorry, I give up. I can't see how to do it elegantly. I guess it's just a poor fit for Ruby. My approach was like this: def ArrayOf(klass, *args) the_array = Array.new(*args) class << the_array # # Redefine ... here # end return the_array end Where "..." is - +(ary) - []=(range, ary) - <<(obj) - []=(idx, obj) - []=(start, length, obj) - push(obj) - unshift(obj) The methods are grouped like that because you need to typecheck the last argument always. In the first two cases that argument will be an array (and you need to check the type of all the elements). For the rest you need to typecheck a single object. []= is a special case. The last argument can be an object OR an array. I think the approach of using a singleton class is good, because you can access the underlying Array method with "super". My first though was delegation, or even a blank class with just #method_missing. However, in these cases, the resulting object wouldn't pass the "is_a? Array" test. I want to highlight this: from a singleton class, you can use "super" like in normal inheritance. Keep this in mind if you are redefining methods anytime. I find the pattern alias_method :old_xxx, :xxx def xxx ... old_xxx ... end rather smelly. Much better is class << obj def xxx ... super ... end end I just learned that through this exercise, so I'm glad some good came of it. Gavin