问题描述
class Something
@@variable = 'Class variable'
def give_me
@@variable
end
end
class OtherThing
@variable = 'Instance variable with an interface'
class << self
attr_accessor :variable
end
def give_me
self.class.variable
end
end
p Something.new.give_me
p OtherThing.new.give_me
我想知道的是,我应该使用哪一个?每种都有哪些优点和缺点?
What I want to know is, which one should I use?Which are the benefits and cons of each?
类变量是:
- 除非您进行界面设置,否则为私人
- 在继承之间共享
- 写短片
类实例变量为:
- 公开,因为您必须使用界面才能访问它们
- 在继承之间不共享,但在继承时设置为nil
- 渴望写作
我还有什么想念的?
推荐答案
我最近发现ActiveSupport定义了 class_inheritable_accessor
,它具有class-instance变量的优点,即对象不会跨继承共享,并且在子类化时可以为变量设置默认值.
I recently discovered ActiveSupport defines class_inheritable_accessor
, which does what the class-instance variables do with the advantage that objects are not shared across inheritance, and you can have a default value for the variable when subclassing.
class Foo
class_inheritable_accessor :x, :y
end
Foo.x = 1
class Bar < Foo
end
Bar.x #=> 1
Bar.x = 3
Bar.x #=> 3
Foo.x #=> 1
更多信息此处
仅出于完整性考虑:在提出的两个选项中,我更喜欢使用class-instance变量,因为这通常是预期的行为.
Just for completeness: of the two presented options, I prefer going with the class-instance variables, since is often the expected behavior.
这篇关于我应该在Ruby中为类静态变量使用类变量还是类实例变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!