user266003
user266003

Reputation:

How do I initialize a class variable in Ruby?

For instance:

class MyClass
    @@var1 = '123456'
    def self.var1
        @@var1
    end

    class << self
        attr_accessor :var2
        def self.initialize
          self.var2 = 7890
        end
    end

end

 p MyClass.var1 # "123456"
 p MyClass.var2 # nil

Is there any way to initialize var2?

Upvotes: 0

Views: 8012

Answers (2)

oldergod
oldergod

Reputation: 15010

You could do this if var2 is not a boolean.

class MyClass
  class << self
    attr_writer :var2
  end

  def self.var2
    @@var2 ||= 'my init value'
  end
end

Upvotes: 6

megas
megas

Reputation: 21791

First of all, here's a confusion in class variable and singleton class. When you're doing class << self it doesn't mean you can now get @@var1 as self.var1. I illustrate it by this example

class MyClass

  @@var1 = '123456'

  class << self
    attr_accessor :var1

    def get_var1
      @@var1
    end

    def set_var1
      self.var1 = '654321'
    end
  end
end

MyClass.get_var1 #=> '123456'
MyClass.set_var1 #=> '654321'
MyClass.get_var1 #=> '123456'

As you can see @@var1 is available in the whole class scope but it differs from singleton variable.

A class variable is shared among all objects of a class, and it is also accessible to the class methods. So you can initialize it in any place you find it acceptable. The most simple and understandable is right in the class scope.

class MyClass
  @@var1 = '123456'
  ...
end

Upvotes: 1

Related Questions