From: Mathieu Bouchard Date: 2002-01-11T01:00:26+09:00 Subject: Re: instance variables automatically accessible? On Thu, 10 Jan 2002 cmlr@math.rochester.edu wrote: > Does anyone know the best way to make instance variables in a class > automatically accessible? In other words, how do you avoid writing > attr_accessor :a, :b, :c > I came up with the following way, but I don't like it, since it > uses "eval". > eval "attr_accessor :#{v[1..-1]}" that line can be written: attr_accessor v[1..-1].intern because attr_accessor is a method of the Class class with a Symbol argument. (but note that "alias" and "undef" are not class methods) however your code does not work with attributes that are not created in #initialize; maybe this is not a problem for you; otherwise you'd have to override #method_missing to detect them and create attributes on-the-fly. I also notice that you recreate the same attributes over and over. If every call to #initialize creates the same attributes, then you can optimise things this way: class Class alias oldNew new private :oldNew def new(*args) o = oldNew(*args) unless @attribs_created for v in o.instance_variables attr_accessor v[1..-1].intern end @attribs_created=true end o end end note: @-vars in Class objects are per class; @@-vars are per class-tree, and can be accessed from instances of the classes of that tree. note2: attribute accessors will be duplicated when creating subclasses. it mostly just means a little wasted memory, as attributes of base classes will have redundant accessors which hide each other. the wasted memory is per-class, not per-object, so this is probably not a problem. ________________________________________________________________ Mathieu Bouchard http://hostname.2y.net/~matju