鉴于此代码:
class Mammal
@@class_name = "mammal"
def self.class_name
@@class_name
end
end
class Dog < Mammal
@@class_name = "dog"
def self.class_name
@@class_name
end
end
Dog.class_name
# => dog
Mammal.class_name
# => dog
为什么这是红宝石的特征?似乎类变量遵循与实例变量不同的范围。类变量的范围是否在其整个继承链中共享?如果是这样,为什么呢?它们是单独的类,应该有作用域类变量,不是吗?我错过了什么?
答案 0 :(得分:0)
类变量在整个类层次结构中共享,它们不会被继承,因此赋值顺序很重要:
class Mammal
@@class_name = "mammal"
def self.class_name
@@class_name
end
end
class Dog < Mammal
@@class_name = "dog"
def self.class_name
@@class_name
end
end
class Mammal
@@class_name = "fish"
end
Dog.class_name # fish
Mammal.class_name # fish
<强>更新强>
使用类实例变量,类变量很棘手:
class Mammal
@class_name = "mammal"
def self.class_name
@class_name
end
end
class Dog < Mammal
@class_name = "dog"
def self.class_name
@class_name
end
end
Dog.class_name # dog
Mammal.class_name # mammal