@@class variables and subclasses

OK, this has been causing me problems:

class A
    @@index = Index.new(...)
end #c:A


class B < A
    @@index = Index.new(...)
end #c:B

This has the unfortunate problem of causing @@index in class A to be
replaced with the new one in class B, because @@class variables are
shared between classes. This is annoying. In some cases I can use
@instance variables for a class, but in this case I need to access the
class index (@@index) in instance methods, and it’s not an instance
variable. (I can’t access class @instance variables from instance
functions that I know of.)

Ideas?

···


Ryan Pavlik rpav@users.sf.net

“Elfland? Mo’ like pansyland.” - 8BT

Ryan Pavlik wrote:

OK, this has been causing me problems:

class A
    @@index = Index.new(...)
end #c:A


class B < A
    @@index = Index.new(...)
end #c:B

This has the unfortunate problem of causing @@index in class A to be
replaced with the new one in class B, because @@class variables are
shared between classes. This is annoying. In some cases I can use
@instance variables for a class, but in this case I need to access the
class index (@@index) in instance methods, and it’s not an instance
variable. (I can’t access class @instance variables from instance
functions that I know of.)

Ideas?

This is one approach, but it makes everything public, unlike @@index.
(You could make the attr_accessor protected, though.)

class A
class <<self; attr_accessor :index; end
@index = “A’s index”
end

class B < A
@index = “B’s index”
end

A.index
B.index

class A
def index
self.class.index
end
end

A.new.index
B.new.index

Try this …

class A
class << self
attr_accessor :index
end

def f
  self.class.index = Index.new
  # or
  A.index
end

end

And if B inherits from A, it A.index and B.index are independent.

···

On Mon, 2003-04-07 at 20:42, Ryan Pavlik wrote:

OK, this has been causing me problems:

class A
    @@index = Index.new(...)
end #c:A


class B < A
    @@index = Index.new(...)
end #c:B


– Jim Weirich jweirich@one.net http://w3.one.net/~jweirich

“Beware of bugs in the above code; I have only proved it correct,
not tried it.” – Donald Knuth (in a memo to Peter van Emde Boas)