简体   繁体   中英

What does @@ mean in Ruby?

As I'm browsing through a Rails source code, it contains the line:

@@autoloads = {}

What does @@ mean in Ruby?

It means to access a class property (a property namespaced to the class), not an instance one (a property that exists for each instantiated object from that class).

In your example, the @@autoloads will persist for the length of your program.

class TestObj
  @@prop = 0
  def get_prop
      @@prop
  end

  def increment_prop
    @@prop += 1   
  end
end

a = TestObj.new
b = TestObj.new

a.increment_prop 

puts b.get_prop # 1

CodePad

@@标识一个类变量。

@@ is nothing but indicating a class variable.

A class variable is a variable that is shared amongst all instances of a class. This means that only one variable value exists for all objects instantiated from this class.

Another way of thinking of thinking of class variables is as global variables within the context of a single class.

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