From: Dan Doel Date: 2003-08-25T18:12:26+09:00 Subject: Re: Class variables - a surprising result Alan Chen wrote: >The beauty of ruby is that you can clean this up if you >really want. > >class Module > # generate "static" variables more like C++ or Java > def attr_reader_static(*syms) > syms.each { |sym| > module_eval( %Q[def self.#{sym}; @#{sym}; end] ) > } > end > > def attr_writer_static(*syms) > syms.each { |sym| > module_eval( %Q[def self.#{sym}=(val); @#{sym} = val; end] ) > } > end > > def attr_accessor_static(*syms) > attr_reader_static(syms) > attr_writer_static(syms) > end >end > > >class Foo > attr_accessor_static :staticvar >end > >Foo.staticvar = 11 >p Foo.staticvar => 11 > Actually, this should be simpler (to read, anyway): class Object def singleton_class class << self self end end end class Module def attr_reader_static(*syms) singleton_class.class_eval { attr_reader *syms } end def attr_writer_static(*syms) singleton_class.class_eval { attr_writer *syms } end def attr_accessor_static(*syms) singleton_class.class_eval { attr_accessor *syms } end end If you want class instance variables, anyway. If you want static variables that act like Java/C++ static variables, I did that in a post elsewhere in this thread (I could look it up if pressed :) ). - Dan