tags:

views:

31

answers:

2
class A
  #define class level attribute called key
  class << self
    attr_accessor :key
  end
end

class B < A
end

B.key = "foo"
B.key # returns "foo"
A.key # returns nil

.

What is the approach if I want A.key to return "foo" in the above scenario?

A: 

Class methods can't be virtual. C'est la vie. When you have a class, you have no virtual table.

Dmitry
+1  A: 

The only way I know is to manually declare the class functions. Subclasses will return the parent's value, but you cannot have them return a different value.

class A
  def self.key
    @@key
  end

  def self.key=(new_val)
    @@key = new_val
  end
end
The Wicked Flea