Ruby 为继承的类分配类变量

Ruby 为继承的类分配类变量,ruby,Ruby,继承类时,我希望将类变量保存到继承类而不是父类。。。就像这样 class Foo def self.inherited klass klass.title = klass.to_s end def self.title= title @@title = title end def self.title @@title end end class Bar < Foo end class Baz < Foo end Bar.tit

继承类时,我希望将类变量保存到继承类而不是父类。。。就像这样

class Foo
  def self.inherited klass
    klass.title = klass.to_s
  end

  def self.title= title
    @@title = title
  end

  def self.title
    @@title
  end
end

class Bar < Foo
end

class Baz < Foo
end

Bar.title # returns `Baz` instead of `Bar`
Baz.title
class-Foo
def self.klass
klass.title=klass.to_
结束
def self.title=标题
@@头衔
结束
def self.title
@@头衔
结束
结束
类Bar

这是一个精心设计的示例,因为在使用它之后,我更想理解它。

您需要将类变量更改为实例变量

class Foo
  def self.inherited klass
    klass.title = klass.to_s
  end

  def self.title= title
    @title = title
  end

  def self.title
    @title
  end
end

class Bar < Foo
end

class Baz < Foo
end

Bar.title  # => "Bar"
Baz.title # => "Baz"
您可以使用和执行以下操作:

如果需要,可以通过在类定义中添加以下内容来初始化类变量(例如,初始化为
nil
):

def self.inherited klass
  klass.class_variable_set(:@@title, nil)
end

所以我想理解的是为什么所有3个类都共享同一个类变量。我最初使用的是一个实例变量,但它似乎违反了直觉,因为它意味着这些变量将可用于类的实例。。。。但是由于它是一个类方法,实例变量引用类(类的一个实例?@brewster这就是它的设计方式。类变量将被共享。为什么设计,我不知道。但我可以保证,它是如何工作的。-)我的意思是,从技术上讲,声明了3个类,我试图理解为什么不能在它们之间声明3个独立的类变量。@brewster您可以使用实例变量来实现。如果需要,则需要使用不同的类变量(意味着它们的名称应该不同)。我明白你的下一个问题是什么,这是在本周早些时候提出的。我也回答了,但现在找不到:-(。如果你愿意,你可以从我所有接受的答案中搜索。
class Foo
  def self.title= title
    class_variable_set(:@@title, title)
  end
  def self.title
    class_variable_get(:@@title)
  end
end

class Bar < Foo
end

class Baz < Foo
end

Bar.title = 'Bar'
Baz.title = 'Baz'

Bar.title           #=> "Bar"
Bar.title = "Cat"

Baz.title           #=> "Baz"

Bar.class_variables #=> [:@@title]
Baz.class_variables #=> [:@@title]
Foo.class_variables #=> []

Foo.methods(false) #=> [:title=, :title]
Bar.methods(false) #=> []
Baz.methods(false) #=> []
Bar.title #=> NameError: uninitialized class variable @@title in Bar
def self.inherited klass
  klass.class_variable_set(:@@title, nil)
end