简体   繁体   中英

Why do we prefix class variables with @@ in ruby?

I ran an experiment trying to understand how singletons work.

I don't understand why we prefix class variables with @@ instead of @? As referenced below, if the variable is created inline with the class definition, self is defined as Test, and the variable is a class variable correct? We can then use attr_accessor in the singleton class definition to access it. The @var in initialize appears to be different because self is set to t in the context when it is initialized, so var belongs to t in that context?

This is all very confusing, any help would be appreciated.

class Test
  @var = 99
  attr_accessor :var

  def initialize
    @var = "Whoop" #if this is commented, pri doesn't print anything.
  end

  def pri
    puts @var
  end

  class << self
    attr_accessor :var
  end
end

t = Test.new
puts Test.var # Outputs 99
Test.var = 5
puts Test.var # Outputs 5
puts t.pri # Outputs Whoop

if the variable is created inline with the class definition, self is defined as Test, and the variable is a class variable correct?

No. It is an instance variable of a class. It is not a class variable.

Instance variable is visible only to that instance. Class variable is visible to the class, other ancestry classes, and their instances.

  • @var defined in line 2 is defined for Test (which is an instance of Class class). It is not visible to ancestry classes of Test , nor to instances of them.
  • @@var is defined for Test as well as for its ancestry classes, as well as for their instances. They all share the same @@var .
  • @var defined in line 6 is defined for a certain instance of Test (which is not by itself Test ). It is not visible to Test , nor to other instances of Test .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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