…
Also, every object should have the right to maintain state in instance
variables that are not (easily) visible to other objects. Class
objects should not be penalized in this regard (i.e., by having their
instance variables conflated with something else) just because they
are Class objects.Another way to look at it is that Matz clearly wants these two very
different things to exist, so if @@var were an alias for class <<
self; @var; end, there would presumably be something else ($$var or
^^var or whatever) to represent class variables. So then the question
would arise again: should ^^var be equivalent to class << self; @var;
end, and so on infinitely. I guess the @-similarity leads more quickly
to this kind of question than might be the case otherwise, but it’s
really just a cosmetic detail.
The behavior (scoping rules) of class variables changed a lot (for the
better) between 1.6 and 1.8 - still given murky differences like
···
dblack@superlink.net wrote:
class A
@@rules = false
end
class B < A
@@rules ||= false
@@ruler ||= false # doesn’t throw an exception but
begin
@@ruled &= true # does
rescue => mes
p mes
end
end
class A
@@rules = true
@@ruler = true
end
class B
p @@rules # true
p @@ruler # false
end
I can’t see why ``class_attribute_accessor like’’ methods in
Module with a behavior similar to
class Module
def class_attr_accessor(sym)
sym = sym.to_s
mod = self
module_eval <<-Body
protected
def #{sym}
#{mod}.instance_eval { @#{sym} }
end
def #{sym}=(rhs)
#{mod}.instance_eval { @#{sym} = rhs }
end
Body
end
end
class B
class_attr_accessor :sym
def set=(rhs)
self.sym= rhs
end
end
class C < B
def get
self.sym
end
end
B.new.set = “okay”
p C.new.get # okay
wouldn’t have been enough. Considering that accommodating
class variables complicates Ruby’s scoping rules considerably,
I feel that class variables didn’t buy enough to justify their
existence.
/Christoph