Hi –
Ged Byrne gedb01@yahoo.co.uk wrote in message news:20030822093558.59647.qmail@web10801.mail.yahoo.com…
If this idiom could be replaced with some clear syntax
I think it would be a good thing.
If you want to access these in instance methods,
you need to do:
class Foo
def instance_meth
p self.class.class_eval { @var }
end
end
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
That’s a bit different from just a cleaning-up of the prying into an
instance variable, though; here, the object is giving you accessor
methods, so you’re no longer prying.
I can’t help wondering why the term “static” is coming up so much. It
doesn’t seem a very good fit – nor is there a gap that needs to be
filled, as far as I can see, in the Ruby terminology. Any object can
have instance variables, and those instance variables can, if desired,
be read and/or altered through accessor methods; this is true across
the board, no more or less for Class objects than for any others. All
you have to do is go into the scope of the object’s class or singleton
class, and use the attr_* family. (Alternately, you can define the
methods directly on the object: def obj.a; @x; end and so on.)
We’ve seen several implementations where the accessor method creation
process gets wrapped in one more layer, in the single case of Class
objects, than it does for other objects. I guess some of the incentive
for this is to avoid having to jump up into the singleton class zone
(class << self…). But my impression is that the singling out of
Class objects as a kind of special case, when it comes to their having
instance variables, adds a kind of lump to the language that isn’t
really there and that doesn’t pay its way in terms of clarity.
Besides, to do the “normal” attr_* thing (i.e., with non-class objects),
you have to do:
class C
attr_accessor :a
end
which is in fact the same amount of “extra” typing as:
class << obj
attr_accessor :a
end
Hmmm… I never thought of it quite that way before 
David
···
On Sat, 23 Aug 2003, Alan Chen wrote:
–
David Alan Black
home: dblack@superlink.net
work: blackdav@shu.edu
Web: http://pirate.shu.edu/~blackdav