简体   繁体   English

静态变量与本征类变量相比,Ruby有什么区别?

[英]Static variables versus eigenclass class variables, what's the difference in Ruby?

I guess I'm asking for the difference between @store and @@store in the following: 我想我在以下要求@store@@store之间的区别:

class Test
  @@store = 9 
  class << self
    def set_store(v)
      @store = v
    end
    def store
      @store
    end
    def sstore
      @@store
    end
  end
end

Test.set_store 8
p Test.store # 8 
p Test.sstore # 9

a = Test.new

p a.class.store # 8
p a.class.sstore # 9

Where are static variables attached to if not the eigenclass? 如果不是本征类,静态变量将附加在哪里? Are the two effectively the same in terms of interaction? 两者在交互方面是否有效地相同?

They are both class variables but in an instance you can access only @@store variable. 它们都是类变量,但是在实例中,您只能访问@@ store变量。

Mind that class variables are not thread safe in Ruby, so use Mutex if you plan to use varaible as a Hash. 请注意,类变量在Ruby中不是线程安全的,因此,如果您打算将可变变量用作哈希,请使用Mutex。

Using class instance variable for mutex in Ruby 在Ruby中将类实例变量用于互斥量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM