On Sat, 17 Jul 2004, Hal Fulton wrote:

> Imagine you have a class with methods whose behavior changes
> based on various attributes.
<snip>
>
> Please: Express your opinions.

look at my source for arrayfields - i do exactly this.  the general idea is as
follows

only two methods are added to Array, #fields, and #fields=.  these obviously
get/set the @fields memeber of an array.  however, #fields= is special and
extends (if not already done) the object itself with a module containing code
which overrides some of the index-y array operations with ones that work with
strings, symbols, or whatever the method used to (super).  here some of the
relevant bits (simplified a little):

here we see one method only added to class Array.  this does not affect any
existing or future arrays in the program since none of them use this method:

   class Array
     def fields= fields
       extend ArrayFields unless defined? @fieldset

       @fieldset =
         if ArrayFields::FieldSet === fields
           fields
         else
           ArrayFields::FieldSet.new fields
         end
     end
   end

in ArrayFields we see things like:

   module ArrayFields
     def [](idx, *args)
       if @fieldset and (String === idx or Symbol === idx)
         pos = @fieldset.pos idx
         return nil unless pos
         super(pos, *args)
       else
         super
       end
     end
   end

so all the additional functionality is contrained to this module.  this has the
quite important advantage that if you do this

   require 'arrayfields'

   a0 = [0,1,2]
   a1 = [3,4,5]

   a0.fields = %w(zero one two)

   p a0['zero']
   p a1[0]

only a0 will see a performance hit.  i think this could apply to your
scenario.

cheers.

-a
--
===============================================================================
| EMAIL   :: Ara [dot] T [dot] Howard [at] noaa [dot] gov
| PHONE   :: 303.497.6469
| A flower falls, even though we love it;
| and a weed grows, even though we do not love it. 
|   --Dogen
===============================================================================